user1220022 user1220022 - 2 years ago 509
Python Question

python numpy sort eigenvalues

I am using linalg.eig(A) to get the eigenvalues and eigenvectors of a matrix. Is there an easy way to sort these eigenvalues (and associated vectors) in order?

Answer Source

You want to use the NumPy sort() and argsort() functions. argsort() returns the permutation of indices needed to sort an array, so if you want to sort by eigenvalue magnitude (the standard sort for NumPy arrays seems to be smallest-to-largest), you can do:

import numpy as np

A = np.asarray([[1,2,3],[4,5,6],[7,8,9]])
eig_vals, eig_vecs = np.linalg.eig(A)

eig_vals_sorted = np.sort(eig_vals)
eig_vecs_sorted = eig_vecs[:, eig_vals.argsort()]

# Alternatively, to avoid making new arrays
# do this:

sort_perm = eig_vals.argsort()

eig_vals.sort()     # <-- This sorts the list in place.
eig_vecs = eig_vecs[:, sort_perm]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download