Reputation: 167
I am facing an issue when using MATLAB eig function to compute the eigenvalues and eigenvectors of a symmetric matrix.
The matrix D is
10x10
all diagonal elements = 0.45
all off-diagonal elements = -0.05
When using [vec, val] = eig(D) some of the resulting eigenvectors contain complex numbers (i.e 0.3384 + 0.0052i). I have searched online and I found two related posts on similar issue, but did not help me in finding a solution.
So I tried the same subroutine in Python numpy (numpy.linalg.eigh(D)) and it gave me all real eigenvalues and eigenvectors. The results from Python are correct as I was able to verify my final results with a published paper.
My question is what causes MATLAB to give complex eigenvalues and eigenvectors for a symmetric matrix? Is there a way around it? I can certainly re-write my algorithm in Python, but I would rather avoid that.
Note: if I try 4x4 matrix with all diagonal elements = 0.375 and all off-diagonal elements = -0.125 then MATLAB eig(D) gave all real eigenvalues and eigenvectors.
Thanks in advance for any advice on this issue.
Follow up. The code used to generate D and the eigenvalues/vectors:
P = eye(10) - 1/10;
delta = 1 - eye(10);
A = -0.5 * delta;
D = P*A*P;
[vec val] =eig(D)
Upvotes: 3
Views: 2831
Reputation: 167
I was able to solve the problem using single precision.
P = eye(10) - 1/10;
delta = 1 - eye(10);
A = -0.5 * delta;
D = P*A*P;
D = single(D)
[vec val] =eig(D)
The results now are correct. Thank you all for taking the time responding to my question and thanks for all your suggestions. This is really more of a workaround than a solution. I still do not know why double precision causes complex eigenvectors.
Upvotes: 2
Reputation: 8477
Doing
D = 0.5 * eye(10) - 0.05 * ones(10);
eig(D)
I get
ans =
-2.08166817117217e-17
0.5
0.5
0.5
0.5
0.5
0.5
0.5
0.5
0.5
which is not too bad. The first eigenvalue in the result should obviously be zero, so there's a rounding error, but otherwise the result is as expected. Due to the same issue of limited numerical precision I guess there could eventually be very small complex parts, too, but actually Matlab's eig
should detect symmetry and produce only real-valued eigenvalues.
How exactly did you generate your matrix D
? Maybe it has only approximately the structure you are describing?
Upvotes: 0