C ++ Eigen: why one add-assign but not add for asDiagonal () method

I noticed unexpected behavior in Eigen:

int n=10;  //value is irrelevant 
Eigen::MatrixXd A(n);
Eigen::VectorXd v(n);

//works:
Eigen::MatrixXd B = A;
B += v.asDiagonal();

//error:
Eigen::MatrixXd C = A + v.asDiagonal();

      

In the second case, the compiler complains that there is no suitable one operator+

available using MatrixXd

and a DiagonalWrapper<...>

. (The same is true for other operators).

Is this intended? And if so, is there a neat way around the two-line alternative (assign first and then subtract)?

+3


source to share


2 answers


Unfortunately this is similar to expected behavior (possibly due to optimization reasons, but this is just an assumption). However, you can do the following:



Eigen::MatrixXd C = A + v.asDiagonal().toDenseMatrix();

      

+2


source


You could just write the + operator yourself, like

namespace Eigen {
  template <typename OtherMatrix>
  auto operator+(MatrixXd lhs, OtherMatrix&& rhs)
  {
    return lhs += rhs;
  }
}

      



Note that this will force the argument to be evaluated lhs

, in particular, whatever it might cost to construct a MatrixXd

, which might be the reason the authors of Eigen omitted it.

0


source







All Articles