Eigen Convert Matrix to Vector

user3501255 picture user3501255 · Apr 5, 2014 · Viewed 15.7k times · Source

In MATLAB, the line below converts a Matrix to a Vector.It flattens the matrix column by column into a vector.

myvar(:)

How do I do that with Eigen? The solution should work for any dimension of Matrix.

MatrixXd A(3,2);
VectorXd B(6);
A << 1,2,3,4,5,6;
B << A.col(0), A.col(1); 
//This isn't general enough to work on any size Matrix

Answer

Benoit Steiner picture Benoit Steiner · Apr 6, 2014

Eigen matrices are stored in column major order by default, so you can use simply use Eigen Maps to store the data column by column in an array:

MatrixXd A(3,2);
A << 1,2,3,4,5,6;
VectorXd B(Map<VectorXd>(A.data(), A.cols()*A.rows()));

If you want the data ordered row by row, you need to transpose the matrix first:

MatrixXd A(3,2);
A << 1,2,3,4,5,6;
A.transposeInPlace();
VectorXd B(Map<VectorXd>(A.data(), A.cols()*A.rows()));