在python中使用numpy.linalg.eig之后,对特征值和相关的特征向量进行排序

问题描述:

我正在使用numpy.linalg.eig获取特征值和特征向量的列表:

I'm using numpy.linalg.eig to obtain 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), in a way I know what is the associated eigenvector after the sorting.

我找不到使用python函数执行此操作的任何方法.有什么简单的方法还是我必须编写我的排序版本?

I'm not finding any way of doing that with python functions. Is there any simple way or do I have to code my sort version?

使用

Use numpy.argsort. It returns the indices one would use 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 (that is, complex numbers are sorted according to their real part first, with ties broken by their imaginary part).