Search code examples
c++eigen3

Eigen and lazy evaluation


I'm using Eigen3 in my program for everything related to matrices. I know that Eigen uses lazy evaluations to optimise all calculations. I would like to know if such an operation is optimised in the sense of limited unnecessary computations:

D = (A*B*C)(0,0);

where A,B,C are matrices and D is scalar. In english, I just need one element of the matrix product.

Thank you.


Solution

  • For all coefficient-wise operations, the answer is yes. However, matrix products are special because, for efficiency reasons, they are by default evaluated within temporaries. You can enforce lazy evaluation of a matrix product using lazyProduct:

    double ABij = A.lazyProduct(B)(i,j);
    

    For a "triple" product like A*B*C the situation is more tricky because the nested product will be evaluated anyway (to avoid multiple re-evaluations in the general case), therefore you have to limit it yourself, e.g.:

     A.lazyProduct(B*C.col(j))(i);