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
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.]]