Question

I have encountered a problem in MatLab as I attempt to run a loop. For each iteration in the loop eigenvalues and eigenvectors for a 3x3 matrix are calculated (the matrix differs with each iteration). Further, each iteration should always yield one eigenvector of the form [0 a 0], where only the middle-value, a, is non-zero.

I need to obtain the index of the column of the eigenvector-matrix where this occurs. To do this I set up the following loop within my main-loop (where the matrix is generated):

for i = 1:3
    if (eigenvectors(1,i)==0) && (eigenvectors(3,i)==0)
        index_sh = i
    end
end

The problem is that the eigenvector matrix in question will sometimes have an output of the form:

eigenvectors =

   -0.7310   -0.6824         0
         0         0    1.0000
    0.6824   -0.7310         0

and in this case my code works well, and I get index_sh = 3. However, sometimes the matrix is of the form:

eigenvectors =

    0.0000    0.6663    0.7457
   -1.0000    0.0000    0.0000
   -0.0000   -0.7457    0.6663

And in this case, MatLab does not assign any value to index_sh even though I want index_sh to be equal to 1 in this case.

If anyone knows how I can tackle this problem, so that MatLab assigns a value also when the zeros are written as 0.0000 I would be very grateful!

Was it helpful?

Solution

The problem is, very likely, that those "0.0000" are not exactly 0. To solve that, choose a tolerance and use it when comparing with 0:

tol = 1e-6;
index_sh = find(abs(eigenvectors(1,:))<tol & abs(eigenvectors(3,:))<tol);

In your code:

for ii = 1:3
    if abs(eigenvectors(1,ii))<tol && abs(eigenvectors(3,ii))<tol
        index_sh = i
    end
end

Or, instead of a tolerance, you could choose the column whose first- and third-row entries are closer to 0:

[~, index_sh] = min(abs(eigenvectors(1,:)) + abs(eigenvectors(3,:)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top