【发布时间】:2013-11-26 17:05:15
【问题描述】:
我有一个矩阵说a。我需要得到它的一个子矩阵,它的索引基本上来自主矩阵索引的映射(这个映射不一定是 1-1)。我有以下代码来生成子矩阵,这里的映射被认为是sum。
import numpy as np
def transform(A):
B=np.zeros(A.flatten().shape[0])
for i in range(A.flatten().shape[0]):
multi_idx=np.unravel_index(i,A.shape)
B[np.sum(multi_idx)]=A[multi_idx] #the mapping applied on the indices: B[np.sum(multi_idx)]
return B
A=np.arange(27).reshape([3,3,3])
print A
print transform(A)
有输出:
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]
[24 25 26]]]
[ 0. 9. 18. 21. 24. 25. 26. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
【问题讨论】:
标签: python arrays numpy matrix