I am trying to work out how to sort eigen values and eigen vectors that are consistent with other languages. I use the following code on a covariance matrix:

So basically, the eigen values are sorted in descending order and eigen vectors are also negated in some cases. How can I sort and negate eigen values and eigen vectors so that I get answer that is consistent with MATLAB?

To get the eigenvalues in the same order as in matlab, take eigen_vals[end:-1:1], and eigen_vector[:, end:-1:1]. You cannot predict the sign of a column, because if v is an eigenvector corresponding to the eigenvalue \lambda, then Av=\lambda v. But to an eigenvalue does not correspond a single vector, but a subspace. Together with v, \alpha v (\alpha a scalar) is also an eigenvector corresponding to \lambda. Hence for both \alpha=1 and \alpha=-1 you get an eigenvector for the same eigenvalue.

Thank you. I think in MATLAB, if all elements of eigen vector are negative then MATLAB changes the sign to positive. So just the first eigen vector has all negatives, so MATLAB returns all positives

For the eigenvectors you have roughly three choices:

Try to figure out if you can find a system in how Matlab chooses its signs and adjust Julia’s eigenvectors to match.

Design your own convention for choosing the signs and adjust both Matlab’s and Julia’s eigenvectors to match.

Accept that the eigenvector signs are arbitrary and make sure that the following algorithm steps are invariant to whatever choice happened to be made.

The last option is by far the most sound. Notice also that when you have multiple equal eigenvalues the arbitrariness of choice from the subspace spanned by the corresponding eigenvectors is much larger than just a choice of sign.

But I really don’t undestand why you want the same eigenvectors like in Matlab. If \lambda is multiple of order 2, and the corresponding eigenspace is two dimensional, then you get two eigenvectors corresponding to \lambda, which form a basis in this subspace. But there exists an infinity of such bases. If the matrix is symmetric the basis is orthonormal. Matlab could return two orthonormal eigenvectors (v, w), while Julia another pair (t,s). Hence you cannot find necessarily a correspondence between the eigenvectors recturned by the two languages.

Sorting out the eigen values in descending order and the corresponding eigen vectors was important to me. I was not sure if Julia is using a different sign convention and order of eigne values than MATLAB and Python. Your answer has helped me with my question

Or better: reverse!(eigen_vals) and reverse!(eigen_vector, dims=2)
(Assumming that you don’t mind to modify the output originally given by eigen. Otherwise you can use reverse instead of reverse!.)

Note that the eigen function takes a parameter sortby that is a function specifying how you want them to be sorted. If you want them sorted in descending order by the real part, you can just pass sortby=-: