MATLAB: Order of eigenvalues depending on matrix equation order of operations

eigenvalueeigenvectorflippedorderpcapodproper orthogonal decomposition

When computing eigenvalues of a matrix, the ordering of the eigenvalues are exactly flipped based on the way the matrix was computed. The differing ways include placing the matrix operation inside parentheses and not using parentheses both shown below with B and A respectively.
% N => Scalar
% C => Matrix (NxM)
A = 1/N.*C'*C;
B = 1/N.*(C'*C);
[lambdaA] = eig(A);
[lambdaB] = eig(B);
Given the eigenvalue/eigenvector results of these methods differ by a small amount, this problem is easily solved by sorting of the eigenvalues and matching eigenvectors. From other questions and answers on mathworks it has been stated that eig.m does not order them in any particular way. My concern is that something could be off about the results when the entire order is flipped other than the differing numerical errors carried along by each method. Does anyone have any idea how the entire order could be flipped by this change of method? I have attached my data and a code that computes and visualizes the problem if anyone would like to take a look.

Best Answer

The reason for the difference in this case is that matrix B is exactly symmetric, and matrix A is not. EIG detects if the input is symmetric (by calling issymmetric(A)), and uses a different algorithm in that case.
If the input is symmetric the eigenvalues are returned in sorted order. This is not documented because it is just fallout of the current algorithm used, and not guaranteed to be the case forever. To be safe in future versions, we recommend to always sort the eigenvalues. If the input is not symmetric, the eigenvalues are not sorted.
By the way: Matrix B is symmetric because MATLAB detects that C'*C should have symmetric output because both matrices are equal. Matrix A is equivalent to (1/N.*C')*C, so the * operation does not detect that the output should be symmetric.