Search code examples
c++matrixeigen

What is the correct way to extract a vector from a matrix in Eigen?


I'm a beginner in Eigen, and what I'm doing is to extract different rows from a matrix and do some calculation.

The code looks like this

MatrixXd mat(5, 10);
VectorXd vec1 = mat.row(1);
VectorXd vec2 = mat.row(2);
// do some calculation with vec1 and vec2

So the question is, by doing like VectorXd vec = mat.row(1), there's memory allocation / memory copying which may be bad for performance. As I'm only using it for calculation and definitely won't do any changes to the matrix underneath, Is there a better way to do this?

I tried using Eigen::Block but it appeared that Block doesn't support some matrix operations (I'm not sure).


Solution

  • .row() itself is not bad for performance at all, it is one of Eigen's block expressions.

    Blocks expressions can be used both as rvalues and as lvalues. As usual with Eigen expressions, this abstraction has zero runtime cost provided that you let your compiler optimize.

    If you formulate your calculation in terms of expressions, the compiler can do all types of optimization.

    Here is are some examples:

    mat.row(2) = 2 * mat.row(0) + mat.row(1);
    float x = (mat.row(0) - mat.row(1)).squaredNorm();
    

    With this, you give enough information at compile time that Eigen can optimize.

    Not sure what you mean with Eigen::Block, most common usage should be .block() of a matrix. https://eigen.tuxfamily.org/dox/group__TutorialBlockOperations.html