Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing a diagonal matrix from vector of integers: function eigen

Tags:

c++

eigen

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.

like image 508
Aman Deep Gautam Avatar asked Jun 28 '13 09:06

Aman Deep Gautam


2 Answers

According to this part of the documentation you have quite a few options, the easiest one being

auto mat = vec.asDiagonal();
like image 137
filmor Avatar answered Sep 27 '22 19:09

filmor


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)

like image 29
babrodtk Avatar answered Sep 27 '22 19:09

babrodtk