Search code examples
c++linear-algebraeigen

Efficient Storage for Eigen's DiagonalMatrix type in C++


I want to do matrix multiplication with a dense matrix and a diagonal matrix. The diagonal matrix is generated from a vector using vec.asDiagonal().

I am wondering if the DiagonalMatrix type stores just the diagonal, or is it a dense matrix full of zeroes, except for the diagonal? I imagine that a DiagonalMatrix should be a child of Eigen's SparseMatrix. I searched for documentation and found this

https://eigen.tuxfamily.org/index.php?title=SpecialMatrix#Diagonal_matrix, suggesting a DiagonalMatrix inherits from MatrixBase, and not SparseMatrix. Does this mean the memory storage is inefficient?


Solution

  • DiagonalMatrix stores only the diagonal as a dense vector. Both the return type of vec.asDiagonal() and DiagonalMatrix inherit from DiagonalBase and not MatrixBase (doc). They are essentially the same: one stores a reference to a dense vector whereas the other is the owner of the diagonal vector.