Search code examples
eigen

how to deep copy eigen block into a vector?


I load an Eigen matrix A(5,12), and I would like to assign a new eigen Vector as the first 7 values of the first row of matrix A. Somehow, it doesn't work...

Later I realize that block returns a pointer to the original data. How to deep copy the block into Eigen Vector?

Eigen::MatrixXd A(5,12);
Eigen::VectorXd B(12); B = A.row(0);
Eigen::VectorXd C(7); C = B.head(7);

Solution

  • Block methods like block, col, row, head, etc. return views on the original data, but operator = always perform a deep copy, so you can simply write:

    VectorXd C = A.row(0).head(7);
    

    This will perform a single deep copy. With Eigen 3.4 slicing API, you'll also be able to write:

    VectorXd C = A(0,seqN(0,7));