user929304
user929304

Reputation: 485

Efficient way of sorting eigenvalues and eigenvectors obtained from Eigen

I am using Eigen in order to solve the eigensystem for a symmetric matrix m, an example given as follows:

#include <iostream>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
using namespace std;
using namespace Eigen;
int main()
{
  Matrix3f m(3,3);
  EigenSolver<Matrix3f> es;
  m(0,0) = -0.386087;
  m(1,1) = -0.390147;
  m(2,2) = 0.776234;
  m(0,1) = 0.00813956;
  m(0,2) = 0.0781361;
  m(1,0) = 0.0781361;
  m(1,2) = 0.0986476;
  m(2,0) = 0.0781361;
  m(2,1) = 0.0986476;
  es.compute(m,true);
  cout << "matrix is: " << m << endl;
  cout << "The eigenvalues of A are: " << es.eigenvalues() << endl;
  cout << "The eigenvalues of A are: " << es.eigenvectors() << endl;
}

and the output is:

matrix is:  -0.386087 0.00813956  0.0781361
0.00813956  -0.390147  0.0986476
 0.0781361  0.0986476   0.776234
The eigenvalues of A are: (-0.391002,0)
 (0.789765,0)
(-0.398762,0)
The eigenvalues of A are:   (0.976246,0) (-0.0666485,0)   (0.206158,0)
  (0.200429,0) (-0.0835865,0)  (-0.976136,0)
  (-0.08229,0)  (-0.994269,0)  (0.0682429,0)

Questions:

  1. Is this an efficient use of EigenSolver knowing that my matrix is symmetric?

  2. How could I sort the eigenvalues and accordingly the eigenvectors? (to eventually extract the max eigenval and corresponding vec) Could one do a similar construct as is common in Python?

namely:

idx = eigenValues.argsort()[::-1]   
eigenValues = eigenValues[idx]
eigenVectors = eigenVectors[:,idx]

Upvotes: 2

Views: 3236

Answers (1)

chtz
chtz

Reputation: 18807

  1. Is this an efficient use of EigenSolver knowing that my matrix is symmetric?

No, you should use the SelfAdjointEigenSolver in that case: http://eigen.tuxfamily.org/dox/classEigen_1_1SelfAdjointEigenSolver.html

  1. How could I sort the eigenvalues and accordingly the eigenvectors? (to eventually extract the max eigenval and corresponding vec) Could one do a similar construct as is common in Python?

The SelfAdjointEigenSolver already sorts the eigenvalues (from lowest to highest), i.e. to get the highest Eigenvalue/vector, you need to take the last one.

Having the eigenvalues sorted is possible here, since all eigenvalues are guaranteed to be real-valued (which is not guaranteed for the unsymmetric EigenSolver). Another advantage is that the eigenvectors are guaranteed to form a Ortho-Normal Basis (i.e., the corresponding matrix is unitary/orthogonal).

Upvotes: 4

Related Questions