Python numpy eigenvalues

I use linalg.eig (A) to get the eigenvalues ​​and eigenvectors of the matrix. Is there an easy way to sort these eigenvalues ​​(and related vectors) in order?

+5
source share
2 answers

You want to use the NumPy sort()and argsort(). argsort()returns the permutation of the indices needed to sort the array, so if you want to sort by the value of the eigenvalue (standard sorting for NumPy arrays seems the smallest in size), 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]
+7
source

np.linalg.eigoften returns complex values. You may consider using np.sort_complex(eig_vals).

-2

All Articles