Demo: Computing eigenvalues and eigenvectors of a symmetric matrix

We present a program to compute eigenvalues and eigenvectors of a symetric dense matrix. The matrix is simply defined by its coefficients.

  • As any code using we start by including the main header file of the library. We initialize as a constant the matrix size.

    #include "OFELI.h"
    using namespace OFELI;
                               
    int main(int argc, char *argv[])
    {
       const int n = 6;

  • We next instantiate a dense symmetric (class DSMatrix having size n. We initialize this matrix as the classical matrix of the 2-nd order finite difference discretization of the Laplace operator in 1-D.

       DSMatrix<double> A(n);
       A = 0;
       A(1,1) = 2; A(1,2) = -1;
       for (size_t i=1; i<=n; i++) {
          A(i,i-1) = -1;
          A(i,i) = 2;
          A(i,i+1) = -1;
       }
       A(n,n-1) = -1; A(n,n) = 2;

  • The simplest method to solve an eigenvalue problem is to use the constructor of class EigenProblemSolver using the matrix and a vector that contains on output the eigenvalues. This constructor performs the extraction of eigenvalues. By default, all eigenvalues are computed.

       Vect<double> ev;
       EigenProblemSolver e(A,ev);

  • Now the vector ev contains the eigenvalues. We display its contents and we also display eigenvectors, which are accessible through the member function getEigenVector

       Vect<double> v(n);
       for (int i=1; i<=n; i++) {
          cout << "Eigenvalue #" << i << ": " << ev(i) << endl;
          e.getEigenVector(i,v);
          cout << "Eigen vector:\n" << v;
       }

  • We can also output the number of subspace iterations

       cout << "Nb. of iterations: " << e.getNbIter() << endl;
       return 0;
    }