Sort eigenvalues โ€‹โ€‹and related eigenvectors after using numpy.linalg.eig in python

I use numpy.linalg.eig to get a list of eigenvalues โ€‹โ€‹and eigenvectors:

A = someMatrixArray from numpy.linalg import eig as eigenValuesAndVectors solution = eigenValuesAndVectors(A) eigenValues = solution[0] eigenVectors = solution[1] 

I would like to sort my eigenvalues โ€‹โ€‹(e.g., from lowest to highest), how do I know what is an associated eigenvector after sorting.

I find no way to do this with python functions. Is there any easy way or do I need to encode my sort version?

+47
python sorting numpy
Nov 11 '11 at 10:53
source share
2 answers

Use numpy.argsort . It returns the indexes that will be used to sort the array.

 import numpy as np import numpy.linalg as linalg A = np.random.random((3,3)) eigenValues, eigenVectors = linalg.eig(A) idx = eigenValues.argsort()[::-1] eigenValues = eigenValues[idx] eigenVectors = eigenVectors[:,idx] 

If the eigenvalues โ€‹โ€‹are complex, the sort order is lexicographic (i.e. complex numbers are first sorted by their real part, with bundles broken by their imaginary part).

+76
Nov 11 '11 at 11:04
source share

The above unutbu answer is very clear and concise. But, here is another way we can do that is more general and can be used for lists as well.

 eval, evec = sp.eig(A) ev_list = zip( eval, evec ) ev_list.sort(key=lambda tup:tup[0], reverse=False) eval, evec = zip(*ev_list) 

This tup [0] is an eigenvalue based on which sorting sorts the list.

reverse = False to increase the order.

+3
Oct 12 '13 at 3:14
source share



All Articles