Search code examples
c++eigen

Constructing a diagonal matrix from vector of integers: function 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.


Solution

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

    auto mat = vec.asDiagonal();