I have a vector of integers and I want to construct a diagonal matrix with vectos's element as diagonal entries of the matrix. For example: if vector is 1 2 3
the diagonal matrix would be:
1 0 0
0 2 0
0 0 3
The naive way to do it would be just iterate over it and set elements one by one. Is there no other direct way to do this in eigen
. Also after constructing the diagonal I want to calculate the inverse(which is just reversing the diagonal entries) but there does not seem to be a way to do this too(directly, which would be optimized way too) in the library itself.
I have looked up the documentation of diagonal matrices in eigen
library but it seems like that there is no way .If I have missed something obvious while reading the documentation please point out.
Any help appreciated.
According to this part of the documentation you have quite a few options, the easiest one being
auto mat = vec.asDiagonal();
You should use proper types with Eigen, unless you really know what you're doing
//Create a 4x4 diagonal matrix from the vector [ 5 6 7 8 ]
Eigen::Vector4d vec;
vec << 5, 6, 7, 8;
Eigen::DiagonalMatrix<double, 4> mat = vec.asDiagonal();
Using auto is a really slippery slope where you typically have no idea what the compiler uses as the type, and coupled with Eigen, this is one of the common sources of tricky-to-find errors (see https://eigen.tuxfamily.org/dox/TopicPitfalls.html)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With