在网格上排序的特征值和特征向量
Sorted eigenvalues and eigenvectors on a grid
我在 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
它给出了正确的答案,但不是正确的形状,eveco 的形状应该是 (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.]]
这个怎么样,它在未排序的维度上放置一个开放网格以防止它们被复制(用以下代码替换代码的最后四行)。
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.]]
我在 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
它给出了正确的答案,但不是正确的形状,eveco 的形状应该是 (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.]]
这个怎么样,它在未排序的维度上放置一个开放网格以防止它们被复制(用以下代码替换代码的最后四行)。
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.]]