Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python numpy sort eigenvalues

Tags:

python

numpy

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?

like image 220
user1220022 Avatar asked Oct 09 '22 04:10

user1220022


1 Answers

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]
like image 183
ely Avatar answered Oct 13 '22 11:10

ely