MATLAB: The Eigenvalues of a large matrix don’t cross each other when plotted

eigenvalues

I am trying to plot the eigenvalues of a matrix in accending order w.r.to some parameter. The matrix has large dimension. Here various eigenvalues of the matrix is not actually crossing at some points rather it seems to be repeling each other at those points. But it is expected that it should cross over each other at those points. I don't understand why this is happening. Please somebody help me. The matlab code is given below.
om=1.0;
om0=0;
dlt=0.5;
n=50;
I1=eye(n);
I2=eye(2);
matdimension= n-1;
tempvector = 0:1:matdimension;
tempvector = sqrt(tempvector);
tempmatrix = diag(tempvector);
anni= circshift(tempmatrix,-1);
crea = anni';
num=crea*anni;
c=crea+anni;
sigx=[0,1;1,0];
sigz=[1,0; 0,-1];
lm=0:0.01:1.0;
w1 = zeros(size(lm));
w2 = zeros(size(lm));
w3 = zeros(size(lm));
w4 = zeros(size(lm));
w5 = zeros(size(lm));
w6 = zeros(size(lm));
for i = 1:length(lm)
H= om*kron(I2,num) +(dlt./2)* kron(sigz,I1) + lm(i).*(kron(sigx,crea+anni));
l= eig(H);
v= sort(l);
w1(i)=v(1);
w2(i)=v(2);
w3(i)=v(3);
w4(i)=v(4);
w5(i)=v(5);
w6(i)=v(6);
end
plot(lm,w1,'k',lm,w2,'r',lm,w3,'b',lm,w4,'g',lm,w5,'y',lm,w6,'c')

Best Answer

Yes, this is a very common problem with MATLAB's eig function, and John has created this excellent package to solve this problem: https://www.mathworks.com/matlabcentral/fileexchange/22885-eigenshuffle . This maintains consistency in the order of eigenvalues. Try the following code
om=1.0;
om0=0;
dlt=0.5;
n=50;
I1=eye(n);
I2=eye(2);
matdimension= n-1;
tempvector = 0:1:matdimension;
tempvector = sqrt(tempvector);
tempmatrix = diag(tempvector);
anni= circshift(tempmatrix,-1);
crea = anni';
num=crea*anni;
c=crea+anni;
sigx=[0,1;1,0];
sigz=[1,0; 0,-1];
lm=0:0.01:1.0;
H = zeros(100, 100, length(lm));
for i = 1:length(lm)
H(:,:,i) = om*kron(I2,num) +(dlt./2)* kron(sigz,I1) + lm(i).*(kron(sigx,crea+anni));
end
[~, e] = eigenshuffle(H);
e = flipud(e);
w1 = e(1,:);
w2 = e(2,:);
w3 = e(3,:);
w4 = e(4,:);
w5 = e(5,:);
w6 = e(6,:);
plot(lm,w1,'k',lm,w2,'r',lm,w3,'b',lm,w4,'g',lm,w5,'y',lm,w6,'c')