14

I use a function at Matlab:

[V,D] = eig(C);

I see that V and D are always sorted ascending order. Does it always like that or should I sort them after I get V and D values?

Amro
  • 123,847
  • 25
  • 243
  • 454
kamaci
  • 72,915
  • 69
  • 228
  • 366
  • Why don't you use `sort()` to make `c` purposely descending and ascending. Then see what `eig` does to it. So you can come to a conclusion by experimenting or reading the manual. But I like the eariler :D Check this [mathworks question](http://www.mathworks.com/matlabcentral/newsreader/view_thread/156868) – bonCodigo Dec 04 '12 at 13:52
  • I'll bet it depends on the algorithm used. – duffymo Dec 04 '12 at 13:52

2 Answers2

32

If you want to guarantee sorted-ascending values, just do an extra

if ~issorted(diag(D))
    [V,D] = eig(A);
    [D,I] = sort(diag(D));
    V = V(:, I);
end

to sort them the way you want.

Alternatively, use eigs:

[V,D] = eigs(A,size(A,1)-1)
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
  • 4
    @kamaci Not that I'm complaining, but why would you accept *my* answer, and not the *better* answer by woodchips? – Rody Oldenhuis Dec 04 '12 at 14:28
  • I agree that your answer is the best for me. – xuhdev Apr 21 '13 at 22:34
  • (I would pedantically argue that `I` is a misleading variable name, and would opt for one which better reflects it is simply an array of indices, like `inds`, and not an identity matrix) – Anti Earth Jul 13 '16 at 07:37
  • `eigs` does not take care of the sign. Say `A` is 5 by 5. How to get the smallest 3 eigenvalues (not magnitude) and the corresponding eigenvectors for `eigs` (not `eig`)? – Ka Wa Yip Aug 19 '16 at 08:34
  • 1
    It seems it does not always sort the same way. When you ask for all the eigenvalues, it is default descending, and otherwise it is ascending. IDK if this is an error or something in documentation I missed, but to be safe, I recommend adding the argument 'largestabs' – Alex Li Jul 20 '18 at 19:47
25

V is NOT sorted in any order, except to correspond to the order of the associated eigenvalues. But perhaps you did not mean that.

The eigenvalues TEND to be in descending order, but this is not assured at all. They tend to be in order because the largest tend to trickle out of the algorithm on top. Eig has no sort at the end to ensure that fact.

I might point out the eigenshuffle tool, designed to take a sequence of eigenproblems, then resorting the eigenvalues (and the corresponding eigenvectors) so they are consistent along the sequence.

If you really need them certainly in decreasing order, then do a sort to ensure that fact. Make sure you also sort the vectors in the same order.

  • 1
    Should this read "TEND to be in *increasing* order"? That is my observation, anyway. – Jed Jan 27 '23 at 20:21