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!!
To build a block of matrix, use the numpy.block () method in Python Numpy. Blocks in the innermost lists are concatenated along the last dimension (-1), then these are concatenated along the secondlast dimension (-2), and so on until the outermost list is reached. Blocks can be of any dimension, but will not be broadcasted using the normal rules.
Python | Numpy matrix.sum() With the help of matrix.sum() method, we are able to find the sum of values in a matrix by using the same method. Syntax : matrix.sum() Return : Return sum of values in a matrix. Example #1 : In this example we are able to find the sum of values in a matrix by using matrix.sum() method.
With the help of Numpy matrix.mean () method, we can get the mean value from given matrix. In this example we can see that we are able to get the mean value from a given matrix with the help of method matrix.mean (). Writing code in comment?
This might sound a little confusing, so think about what np.sum is doing. When NumPy sum operates on an ndarray, it’s taking a multi-dimensional object, and summarizing the values. It either sums up all of the values, in which case it collapses down an array into a single scalar value.
In [1952]: test=np.arange(81).reshape(9,9)
In [1953]: res=np.zeros((3,3))
In [1954]: for i in range(3):
...: for j in range(3):
...: res[i,j]=test[3*i:3*(i+1),3*j:3*(j+1)].mean()
In [1955]: res
Out[1955]:
array([[ 10., 13., 16.],
[ 37., 40., 43.],
[ 64., 67., 70.]])
With reshape and sum or mean on selected axes:
In [1956]: test.reshape(3,3,3,3).mean(axis=(1,3))
Out[1956]:
array([[ 10., 13., 16.],
[ 37., 40., 43.],
[ 64., 67., 70.]])
sum/mean allows us to specify 2 or more axes at a time, but it can also be done with repeated single axis applications.
test.reshape(3,3,3,3).mean(3).mean(1)
For the 3d array, these work
test.reshape( 2,3,3,3,3).mean((2,4))
test.reshape(-1,3,3,3,3).mean((2,4))
The -1
preserves the original 1st dimension (or in the case of a 2d test
, it adds a size 1
dimension).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With