Eigenvalue ordering unexpectedly different in two cases

Hello everyone, I am probably making a subtle mistake or assumption somewhere as I cannot understand why the following two eigendecompositions do not return the eigenvalues in the same order.
Could somebody please explain to me why this is the case?

Here is a MWE:

using Distributions, LinearAlgebra

D = Diagonal([2.0; 1.0])

Q = MvNormal([0.0;0.0], D)

eigen(cov(Q)).values # 1st eigenvalue decomposition. I get eigenvalues ordered as 1.0, 2.0

eigen(D).values # 2nd eigenvalue decomposition. I get eigenvalues ordered as 2.0, 1.0

Many thanks.

For Diagonal it always returns the eigenvalues in the order they appear in the diagonal, so that the eigenvectors are the identity matrix. For most other matrix types it sorts the eigenvalues in ascending order (by real part), though you can change this using the eigsortby argument.

This is explained in the docs for eigen, which say:

By default, the eigenvalues and vectors are sorted lexicographically by (real(λ),imag(λ)) . A different comparison function by(λ) can be passed to sortby , or you can pass sortby=nothing to leave the eigenvalues in an arbitrary order. Some special matrix types (e.g. Diagonal or SymTridiagonal) may implement their own sorting convention and not accept a sortby keyword.

1 Like

Thank you. I read the help multiple times, but somehow overlooked the mention of Diagonal.