c++eigendiagonal

Inverting Diagonal matrix object in Eigen library (C++)


I'm trying to extract the diagonal from a matrix and then invert it using the Eigen library in C++. This should be the component-wise inverse and should be computed fairly quickly. However the following does not seem to compile:

Eigen::MatrixXd A = /* some matrix */;
Eigen::Diagonal<Eigen::MatrixXd> D = A.diagonal().;
Eigen::MatrixXd D_inv = D.inverse();

It seems that there is no "inverse()" method on the Diagonal object. The exact error I'm getting is:

Undefined symbols for architecture x86_64:
  "Eigen::MatrixBase<Eigen::Diagonal<Eigen::Matrix<double, -1, -1, 0, -1, -1>, 0> >::inverse() const"

Is there a simple way to calculate the inverse, without doing it manually?


Solution

  • The Diagonal type just represents a view of the values on the diagonal and doesn't actually construct a new matrix. A diagonal matrix can be obtained from the Eigen Diagonal object via the asDiagonal() method. Here's a full example:

    #include <Eigen/Dense>
    int main() {
        Eigen::Matrix3d A {{-1, 1, 1}, {1, -1, 1}, {1, 1, 1}};
        const auto diagonalObject = A.diagonal();
        const auto diagonalMatrix = diagonalObject.asDiagonal();
        const auto inverse = diagonalMatrix.inverse();
        return 0;
    }