Add Matrix and Diagonal Matrix to Eigen3

I want to add elements to the diagonal of an Eigen :: MatrixXd object with the Eigen3 library (version 3.3.2).

For both optimization and constant use, I want to do this by adding a diagonal matrix to the original, for example

const MatrixXd a(2,2); a << 1, 2, 3, 4;
const VectorXd v(2); v << 10, 20;
const MatrixXd b = a + v.asDiagonal();

      

But that doesn't work: I get a compiler error saying that doesn't exist operator+

. Adding two MatrixXd

does work, so I expect it to behave for a diagonal specialization.

Removing the constant doesn't help. The use of static size matrices is irrelevant, so it is not a dynamic sizing element. And the explicit construction DiagonalMatrix

, not the usage DiagonalWrapper

returned asDiagonal()

, also gives the same error.

Multiplication is well-formed for these types: it MatrixXd c = a * v.asDiagonal();

compiles and works just fine. Am I doing something wrong or operator+(Matrix,DiagonalMatrix)

just missing from the library?

+3


source to share


1 answer


Thanks to @CoryKramer for linking to an equivalent question asked and answered on the KDE / Eigen forum: https://forum.kde.org/viewtopic.php?f=74&t=136617 Here's a summary for posterity:

The "normal" addition of Eigen Matrix

and either a DiagonalMatrix

or is DiagonalWrapper

not supported, and the addition of multiplication or join is +=

fine. +=

not an option if you are trying to work with const objects, but create an explicit one Matrix2d

from the call asDiagonal()

- why haven't I thought about it? - works nicely:



MatrixXd b = a + Matrix2d(v.asDiagonal());

      

I guess there are potential performance penalties, so this is not supported without type building. But they are unlikely to be any worse than the dirty alternative to manually looping through diagonal indices.

+1


source







All Articles