1

I am working on MATLAB problems from my textbook and one of the problems asks me to use the eig command in MATLAB, compute the matrices V and D such that A = V * D * inv(V). Knowing that the first column of V corresponds to the first eigenvalue D(1,1) and so on, I need to reorder the diagonal entries of D so that the real part is increasing down the diagonal and reorder the columns of V accordingly so that A = V * D * inv(V) still holds. Here's what I have written so far:

r = RandStream('mt19937ar','Seed',1234);
A = r.randn(10,10)+1j*r.randn(10,10);
[V,D] = eig(A);

for tt = 1:9
    if (real(D(tt,tt)) > real(D(tt+1,tt+1)))
        temp = D(tt,tt);
        D(tt,tt) = D(tt+1,tt+1); 
        D(tt+1,tt+1) = temp;
        tempV = V(1,tt);
        V(1,tt) = V(1,tt+1);
        V(1,tt+1) = tempV;
        if (A == V*D*inv(V))
            break
        end
    end
end

When I tested it, the diagonal elements of D did not change from the original order, I know it might be due to the conditionals I set, but I am not sure what specifically is causing it to not do anything. I also think there might be issues in the way I am reordering the diagonal elements and corresponding eigenvectors. Any feedback or suggestions is appreciated, thank you in advance.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • Why do you need to reorder anything? Please read the documentation to `eig`: https://www.mathworks.com/help/matlab/ref/eig.html – Cris Luengo Nov 30 '19 at 23:02
  • Also note that exact equality comparison is unreasonable. There will always be floating-point rounding errors. `A*V-D*V` should be very small, but will likely not be exactly 0. – Cris Luengo Nov 30 '19 at 23:03

1 Answers1

0

Your code has multiple problems:

  • You need two for-loops for sorting.
  • You are only swapping first element of eigenvectors, use V(:, tt) for whole column.
  • V*D*inv(V) will never be exactly equal to A (see this).

To sort eigenvalues by their real parts, try this:

clc;
r = RandStream('mt19937ar','Seed',1234);
n = 10;
A = r.randn(n)+1j*r.randn(n);
[V,D] = eig(A);
d = diag(D, 0); % get eigenvalues in a vector
[~, I] = sort(real(d)); % get index of eigenvalues after sorting
D2 = diag(d(I)); % get sorted eigenvalues as diagonal matrix
V2 = V(:, I); % reorder eigenvectors to match sorted eigenvalues
any(any(abs(A - V2*D2*inv(V2)) > 1e-14)) % test sorted eigenvalues and eigenvectors
saastn
  • 5,717
  • 8
  • 47
  • 78