I would like to perform some simple calculation on the block matrix (or more generally on the d-dim nd.array). Something like this:
In the picture, capital letters represent a 3 by 3 block matrix, and lower case letters are numbers (mean or sum of block matrices).
Currently, I only know how to do this by using for loop
import numpy as np
test_matrix = np.arange(81).reshape(9,9)
a = np.zeros((3,3))
for i in range(3):
for j in range(3):
a[k,i,j] = test_matrix[3*i:3*(i+1),3*j:3*(j+1)].mean()
print a
But it gets slow if my matrix gets bigger or multi-dimensional, such as the following:
test_matrix = np.arange(81*2).reshape(2,9,9)
a = np.zeros((2,3,3))
for k in range(2):
for i in range(3):
for j in range(3):
a[k,i,j] = test_matrix[k,3*i:3*(i+1),3*j:3*(j+1)].mean()
print a
Is there any better way to perform this kind of tasks?
Thanks a lot!!