I would like to get an array which is the sum of the sub matrices in an array.
For example, lets say we have a 3x3 matrix, where each item contains a 2x2 sub matrix:
matrix = np.array([[[[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],[27,28]], [[29,30],[31,32]], [[33,34],[35,36]]]])
which looks like:
[[[[ 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]
[27 28]]
[[29 30]
[31 32]]
[[33 34]
[35 36]]]]
One way to get the answer is using list comprehension
ans = [ [ np.sum(sub_matrices) for sub_matrices in row ] for row in matrix ]
which will be:
[[10, 26, 42], [58, 74, 90], [106, 122, 138]]
I was wondering if there is a better way to get this result. Maybe using some numpy function built in?