Search code examples
eigen

Multiplying by diagnonal matrix (provided as vector) in Eigen


Given a matrix A and a vector d that represents the diagonal of a diagonal matrix D, what would be the best (i.e. simplest without compromising performance) Eigen expression for D*A in terms of only d and A?

Constructing D (as a dense matrix) and doing D*A seems inefficient as it would involve unnecessary multiplications by zero. The rows of A simply need to be scaled by the corresponding elements of d.

Should I convert to array and scale the rows or does Eigen provide for diagonal matrices to be constructed and multiplied in a way that avoids unnecessary overhead?


Solution

  • You can use an Eigen::DiagonalMatrix, as Damien suggested. Alternatively, if you're already given an Eigen::Vector (or Map), you can use d.asDiagonal() as follows:

    Eigen::VectorXf d;
    Eigen::MatrixXf a, b;
    b = d.asDiagonal() * a;