Search code examples
c++sparse-matrixeigendiagonal

How can I multiply two Eigen::DiagonalMatrix and ad the result to an Eigen::SparseMatrix?


I'm trying to write a solver for a linear system, and coming from Matlab/NumPy and the like, I find Eigen's types a bit limited.

My current issue resolves around this:

D * DD + S

Where D and DD are of type Eigen::DiagonalMatrix<double, Eigen::Dynamic, Eigen::Dynamic> and S is an Eigen::SparseMatrix`.

Is there an (efficient) way to do this? It seems rather basic so I must be missing something. I'm willing to give up D and DD being DiagonalMatrix and them being SparseMatrix instead, as long as the above expression is complicated too much.


Solution

  • Assuming the sparse matrix S already has non-zero coefficients along the diagonal you can do:

    S.diagonal() += D.cwiseProduct(DD);