This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Square Root of a matrix

Tags: None
(comma "," separated)
esum
Registered Member
Posts
2
Karma
0

Square Root of a matrix

Tue Dec 06, 2011 8:26 pm
I'm new to Eigen and relatively new to C++, so please bear with me. Is there an easy way to take the square root of a symmetric matrix using Eigen? I couldn't seem to find anything in the library.

I can find the square root by taking the eigenvalue decomposition (EVD).
Let A = Q*D*inv(Q) be the EVD of A. Then sqrtA = Q*sqrt(Dinv)*inv(Q) is the square root of the matrix.

I tried doing this manually, but I keep getting confused about which matrix/vectors can use which methods.

For example, this doesn't work:
Code: Select all
  MatrixXf a_matrix= MatrixXf::Random(3,3);
  MatrixXcf sqrt_a = MatrixXcf(3,3);
 
  EigenSolver<MatrixXf> es(a_matrix, true);
  MatrixXcf V = es.eigenvectors();
  VectorXcf Dv = es.eigenvalues();
  MatrixXcf sqrtD(a_matrix.cols(), a_matrix.rows());
  for(int i =0; i<a_matrix.cols(); i++)
    {
      sqrtD(i,i) = sqrt(Dv[i]);
    }
  MatrixXcf sqrt_a = V*sqrtD*V.inverse();
  cout<<sqrt_a<<endl;
jitseniesen
Registered Member
Posts
204
Karma
2

Re: Square Root of a matrix

Tue Dec 06, 2011 9:23 pm
That looks quite okay to me. There are some minor problems: your declare sqrt_a twice, and you should make sure that the off-diagonal entries of sqrtD are zero (matrices are not automatically initialized to be zero). But after that the program does compute the square root of the matrix. What exactly is the problem?

You can compute sqrtD in one go with: sqrtD = Dv.cwiseSqrt().asDiagonal()

There are two routines in the library for computing the square root. For symmetric matrices, SelfAdjointEigenSolver::operatorSqrt() does pretty much the same as what you do (computing eigenvalues and eigenvectors); see http://eigen.tuxfamily.org/dox-devel/cl ... 8b2d2b0775 . For general matrices, you need to use the MatrixFunctions module in unsupported, see http://eigen.tuxfamily.org/dox-devel/un ... odule.html , and then you can compute the square root of a_matrix as a_matrix.sqrt(); see http://eigen.tuxfamily.org/dox-devel/un ... xbase_sqrt .

In my experience, the template-heavy code in Eigen means that it does take a while to get used to Eigen and to be able to understand the error messages that the compiler spits out when you do something wrong.


Bookmarks



Who is online

Registered users: Bing [Bot], Google [Bot], Yahoo [Bot]