image thumbnail
from Rootshuffle.m by Alberto
Function that orders the roots/eigenvalues

rootshuffle(A)
function [root] = rootshuffle(A)

r=size(A);
if (length(r)~=2)
    error('The argument must be a 2D array nxp where p is the number of roots');
else
    root=zeros(r(1),r(2));
    p=r(2);
    for k=1:r(1)
        r=A(k,:);
        if k~=1
            dist=abs(diag(root(k-1,:))*ones(p)-ones(p)*diag(r));
            [w,idx]=min(dist);
            for i=1:length(idx)
                doppi=find(i==idx,2);
                if length(doppi)==2
                    for j=1:length(idx)
                        w=find(j==idx,1);
                        if isempty(w)
                            idx(doppi(1))=j;
                        end
                    end
                    for j=k-1:-1:1
                        if root(j,idx(doppi(1)))~=root(j,idx(doppi(2)))
                            break;
                        end
                    end
                    [w,ind1]=max(r(doppi));
                    [w,ind2]=max(root(j,idx(doppi)));
                    if ind1~=ind2
                        idx(doppi)=fliplr(idx(doppi));
                    end
                end
            end
            for i=1:length(r)
                root(k,idx(i))=r(i);
            end
        else
            root(k,:)=r;
        end
    end
end

Contact us