在网格上排序的特征值和特征向量

时间:2017-04-03 21:32:55

标签: python sorting numpy datagrid lapack

我在3d网格上的每个点都有一个矩阵。我需要计算每个点的特征值和特征向量,并按特征值的升序对它们进行排序。我使用python在下面编写了以下测试用例,我能够对特征值进行排序,但相关的特征向量具有更大的维度。

import numpy as np
from numpy import linalg as LA
n = 2
a = np.zeros((3,3,n,n,n))
a[:,:,0,0,0] = [[5,0,0],[0,1,0],[0,0,3]]
a[:,:,1,1,1] = [[2,0,0],[0,3,0],[0,0,1]]
eigvals,eigvecs = LA.eig(a.swapaxes(0, -1).swapaxes(1,-2))
ev = eigvals.swapaxes(0,-1)
evecs = eigvecs.swapaxes(0,-1).swapaxes(1,-2)
evo = np.sort(ev,axis=0)
print evo[:,0,0,0],evo[:,1,1,1]
print evecs[:,:,0,0,0]
print evecs[:,:,1,1,1]
eveco = evecs[np.argsort(ev,axis=0)]
print np.shape(eveco)
print eveco[:,0,0,0,:,0,0,0] # decided after knowing the shape
print eveco[:,1,1,1,:,0,0,0] # decided after knowing the shape

它给出了正确的答案,但形状不正确,依维柯的形状应为(3,3,2,2,2):

[ 1.  3.  5.] [ 1.  2.  3.]
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]
(3, 2, 2, 2, 3, 2, 2, 2)
[[ 0.  1.  0.]
 [ 0.  0.  1.]
 [ 1.  0.  0.]]
[[ 0.  0.  1.]
 [ 1.  0.  0.]
 [ 0.  1.  0.]]

1 个答案:

答案 0 :(得分:0)

如何做到这一点,它在未排序的维度上放置一个开放网格,防止它们被复制(用以下代码替换代码的最后四行)。

eveco = evecs[(np.argsort(ev,axis=0)[:, None, ...],) + tuple(np.ogrid[:3,:n,:n,:n])]
print np.shape(eveco)
print eveco[:,:,0,0,0]
print eveco[:,:,1,1,1]

输出(仅限新代码):

(3, 3, 2, 2, 2)
[[ 0.  1.  0.]
 [ 0.  0.  1.]
 [ 1.  0.  0.]]
[[ 0.  0.  1.]
 [ 1.  0.  0.]
 [ 0.  1.  0.]]