Building a diagonal matrix from an integer vector: function

I have a vector of integers and I want to build a diagonal matrix with the vectos element as the diagonal elements of the matrix. For example: if the vector is 1 2 3 , the diagonal matrix will be:

 1 0 0 0 2 0 0 0 3 

The naive way to do this is to simply iterate over it and set the elements one by one. There is no other direct way to do this in eigen . In addition, after constructing the diagonal, I want to calculate the inversion (which simply changes the diagonal entries), but there seems to be no way to do this either (directly, which would also be optimized) in the library itself.

I looked through the documentation of diagonal matrices in the eigen library, but it seems that there is no way. If I missed something obvious while reading the documentation, please indicate.

Any help was appreciated.

+6
source share
3 answers

In accordance with this part of the documentation , you have several options, the simplest of which is

 auto mat = vec.asDiagonal(); 
+10
source

You should use the correct types with Eigen if you really don't know what you are 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 usually don’t know what the compiler uses as a type, and when combined with Eigen, this is one of the common sources of error errors (see https://eigen.tuxfamily.org/ dox / TopicPitfalls.html )

+1
source

You can also do it the other way around, which also allows you to set super / sub-diagonals.

 MatrixXd A = ...; A.diagonal(0) = values_vector; //for 'main' diagonal A.diagonal(1) = other_values; //for 1st super-diagonal 

See the diagonal reference Eigen Matrix () (there is also an example)

0
source

Source: https://habr.com/ru/post/948309/


All Articles