Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eigen Convert Matrix to Vector

Tags:

matlab

eigen

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
like image 460
user3501255 Avatar asked Apr 05 '14 13:04

user3501255


3 Answers

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()));
like image 143
Benoit Steiner Avatar answered Nov 14 '22 10:11

Benoit Steiner


If you wanna change the matrix values without defining a new variable you can use

Eigen::MatrixXd A(2,3);
A.data()[3] = 1.2

in this case data()[3] will correspond to index A[1,1] of matrix, or read them by

double value = A.data()[5];

so if I write down the whole 2by3 matrix it would be like

A.data()[0]     A.data()[2]    A.data()[4]
A.data()[1]     A.data()[3]    A.data()[5]
like image 39
sina aghli Avatar answered Nov 14 '22 11:11

sina aghli


From the documentation of Eigen itself:

MatrixXd A;
VectorXd B = VectorXd {A.reshaped()};

reshaped produced a linear view of the matrix.

like image 1
Bentoy13 Avatar answered Nov 14 '22 09:11

Bentoy13