MATLAB: Avoiding automatic sorting of eigenvalues

eigeigenvalueMATLABplotsort

I have been trying to find and plot the eigenvalues of a matrix with the following code:
hbar = 6.58211*10^-4;
wph = linspace(0.5/hbar, 1.5/hbar,10000);
w1 = 2000/hbar;
w2 = 2001/hbar;
g = 0;
pump = 50;
clear eigen
for i=numel(wph):-1:1
h= [0 0 pump 0 0;
0 0 0 pump 0;
pump 0 0 0 0;
0 pump 0 0 g;
0 0 0 g w2-w1-wph(i)];
eigen(:,i)=eig(h)*hbar;
end
figure;
plot(wph*hbar, eigen(2,:), '-','Linewidth',2);
hold on;
plot(wph*hbar, eigen(1,:), '--','Linewidth',2);
plot(wph*hbar, eigen(3,:), ':','Linewidth',2);
plot(wph*hbar, eigen(5,:),'Linewidth',2);
plot(wph*hbar, eigen(4,:), '--','Linewidth',2);
xlabel('\omega_{ph}(meV)');
ylabel('Energy (meV)');
grid on;
Symbolically, the eigenvalues obtained are:
pump
pump
-pump
-pump
w2 - w1 - wph
As the value of the variable wph varies, the value of the last eigenvalue changes and it becomes the greatest valued to the least.
Using the above mentioned code, the plot obtained was:
The plot is wrong. The eigenvalues are sorted in between and thus the above result is obtained. Is there any way to stop this?

Best Answer

EIG() does NOT return sorted values; it returns them to the user in the order in which the underlying LAPACK routine calculates them. That they often happen to appear to have been numerically sorted is simply a result of that routine applied to the input array.
In general, there is no such thing as "sorted" or "unsorted" order of the eigenvalues that eig() can know of -- they are merely the set of polynomial roots in the complex plane.
That there is a physical problem associated with the particular array is unknown to eig() and that there is a sequence to come even further from its knowledge base. However, there is a File Exchange submission that may help resolve the problem you're trying to solve -- it isn't unique but there isn't necessarily a hard and fast manner in which it can be solved.
Try John d'Errico's eigenshuffle()
Related Question