Constructing diagonal matrix in eigen

24,962

Solution 1

If you want a standalone diagonal matrix, construct a DiagonalMatrix.

DiagonalMatrix<double, 3> m(3, 8, 6);

// Input after construction
m.diagonal() << 3, 8, 6;

A DiagonalMatrix works like a normal matrix but stores only the diagonal.

Vector3d v(1, 2, 3);
m * v;  // 3 16 18

If you want to make a diagonal matrix out of an existing vector, call .asDiagonal(). Note that .diagonal() returns the diagonal as a vector, so .diagonal().asDiagonal() extract the diagonal part of a matrix and regard it as a diagonal matrix.

Solution 2

Here's a code and its output :

Code:

#include <iostream>
#include "Eigen/Dense"

int main()
{
    Eigen::Matrix< double, 3, 1> v ;
    v << 1, 2, 3;
    Eigen::Matrix< double, 3, 3> m = v.array().sqrt().matrix().asDiagonal();

    std::cout << m << "\n";

    return 0;
}

Output :

  1       0       0
  0 1.41421       0
  0       0 1.73205

As you can see, the output created asDiagonal() from a (31) vector is a normal (33) matrix (that you have to define first), meaning that Eigen holds the 9 elements not just the diagonal ones.

Share:
24,962

Related videos on Youtube

asdfkjasdfjk
Author by

asdfkjasdfjk

Updated on August 20, 2020

Comments

  • asdfkjasdfjk
    asdfkjasdfjk over 3 years

    In eigen, we can create a matrix as

    Matrix3f m;
    m << 1, 2, 3,
         4, 5, 6,
         7, 8, 9;
    

    How can I create a diagonal matrix like the one below

     3, 0, 0,
     0, 8, 0,
     0, 0, 6;
    

    I don't understand how Eigen handle diagonal matrix? Only the diagonal elements are important here. So does Eigen save all 9 elements from above example or Eigen just save only 3 elements 3,8,6. Also, if eigen save all 9 elements then is it necessary to define the matrix as diagonal or is it the same as defining normal 3*3 matrix?

  • asdfkjasdfjk
    asdfkjasdfjk almost 8 years
    so basically there is no difference between Diagonal matrix and normal matrix? Is there any special optimization done for diagonal one?
  • Vtik
    Vtik almost 8 years
    Fixed-size matrices are fully optimized: dynamic memory allocation is avoided, and the loops are unrolled when that makes sense. So, whenever you know the size to be, specify it. After all, diagonal matrix is not that special.
  • Vtik
    Vtik almost 8 years
    please, consider accepting the answer if it solved your original question. cheers.
  • jdh8
    jdh8 almost 8 years
    MatrixBase::asDiagonal() returns a DiagonalWrapper, which holds only the diagonal. The zeros are generated when evaluating into the general matrix m.
  • nimbus3000
    nimbus3000 about 3 years
    what if the size of the diagonal matrix is a variable?

Related