Search code examples
eigen3

Eigen3 Flatten Matrix as Vector


In MATLAB, I can do the following

A = [1 2 3; 4 5 6];
A(:)

to get:

ans =
1
4
2
5
3
6

How would I do this with an Eigen3 Matrix?


Solution

  • The best way is to use Map:

    Map<VectorXd> v(A.data(),A.size());
    

    because in this case Eigen knows at compile time that you now have a 1D vector.

    Of course, the result will depend on the storage order of A, that is, for a column major matrix (the default):

    [1 4 2 5 3 6]^T
    

    and for a row-major one:

    [1 2 3 4 5 6]^T