Efficient way to get an array submatrix that is indexed

I have a matrix a. I need to get its submatrix, basically its indices come from mapping the indices of the main matrix (this map is not necessarily 1-1). I have the following code to generate a submatrix, and here the mapping is considered 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)        

With an exit:

[[[ 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.]
+4
source share
1 answer

np.ogridcan be a convenient way to create expressions based on indexes in an array. For example,

import numpy as np

A = np.arange(27).reshape([3,3,3])
B = np.zeros(A.size)
i, j, k = np.ogrid[0:3, 0:3, 0:3]
B[i+j+k] = A
print(B)

gives

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

Please note that the appointment

B[X] = A

equivalently

B[X.ravel()] = A.ravel()

. , X , B. , , .

+6

All Articles