Search code examples
c++11matrixmatrix-multiplicationeigendiagonal

Diagonal part of matrix and piece-wise square/multiplication in Eigen (C++)


Let A be an nxn real matrix. I would like to get the diagonal part of A and assign it to an Eigen::VectorXd vector. Below, I would like to take the diagonal part of A and assign it to the vector d:

Eigen::MatrixXd A(n,n);
A.setRandom();

Eigen::VectorXd d(n);
d.setZero();

Does Eigen provide some method for the above operation, or do I need to implement them manually? This is certainly very simple, but I would like it to run as fast as possible.


Solution

  • From this section of the docs, you can retrieve the diagonal simply with

    vec1 = mat1.diagonal();

    The docs also mentions a const version, so you can deduce that this can also be used as read and write access.