Eigen Convert Matrix to Vector

前端 未结 3 1910
独厮守ぢ
独厮守ぢ 2021-01-04 12:41

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

myvar(:)

Ho

相关标签:
3条回答
  • 2021-01-04 13:11

    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()));
    
    0 讨论(0)
  • 2021-01-04 13:26

    Another way to do it is:

    ...
    VectorXd B = A;
    B.resize(B.cols()*B.rows(), 1);
    

    or, if you want the vector in row order:

    ...
    VectorXd B = A.transpose();
    B.resize(B.cols()*B.rows(), 1);
    

    Regards.

    0 讨论(0)
  • 2021-01-04 13:31

    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]
    
    0 讨论(0)
提交回复
热议问题