I am surprised to find out that it's not possible to simply add an Eigen::DiagonalMatrix
to an Eigen::SparseMatrix
:
#include <Eigen/Core>
#include <Eigen/Sparse>
int main()
{
Eigen::Matrix4d M;
M<<1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16;
Eigen::SparseMatrix<double> S = M.sparseView();
Eigen::DiagonalMatrix<double,Eigen::Dynamic> D =
Eigen::VectorXd::LinSpaced(4,1,4).asDiagonal();
Eigen::SparseMatrix<double> T = D+S;
}
will not compile:
error: invalid operands to binary expression ('Eigen::DiagonalMatrix<double, Eigen::Dynamic>' and 'Eigen::SparseMatrix<double>')
Eigen::SparseMatrix<double> T = D+S;
It seems in Eigen 3.3 I can use:
T.diagonal() = D.diagonal() + T.diagonal();
But this doesn't compile for the older (more stable) Eigen 3.2.*:
error: no viable overloaded '='
T.diagonal() = D.diagonal() + T.diagonal();
Do I really have to iterate over the entries and insert them one by one?
Eigen::SparseMatrix<double> T = S;
for(int i = 0;i<T.rows();i++) T.coeffRef(i,i) += D.diagonal()(i);
Update:
Looks like you can also do:
Eigen::SparseMatrix<double> T = Eigen::SparseMatrix<double>(D)+S;
I'm guessing this incurs unnecessary copying.