在网格上排序的特征值和特征向量 [英] Sorted eigenvalues and eigenvectors on a grid

查看:109
本文介绍了在网格上排序的特征值和特征向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a matrix at each point on a 3d grid. I need to calculated the eigen values and eigen vectors at each point and the sort them in ascending order of eigen value. I wrote the following test case below using python, I am able to sort the eigen value but the associated eigen vector is of larger dimension.

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):

It gives right answers, but not right shape, shape of eveco should be (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.]]

推荐答案

如何解决此问题,它在未排序的维度上放置了一个开放式网格,以防止它们重复(将代码的最后四行替换为以下内容).

How about this, it places an open grid on the non sorted dimensions preventing them from being duplicated (replace the last four lines of your code with the following).

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]

输出(仅适用于新代码):

Output (of the new code only):

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

这篇关于在网格上排序的特征值和特征向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆