2

If I knew the dimensions of each square submatrix m (2x2), and that the dimensionality of a large square matrix M was evenly divisible by the dimensionality m: M modulo m == 0.

Is there an efficient way to sum the following matrix M:

M = array([[ 1.,  1.,  1.,  1.],
           [ 1.,  1.,  1.,  1.],
           [ 1.,  1.,  1.,  1.],
           [ 1.,  1.,  1.,  1.]])

Such that the result is:

M' = array([[ 4.,  4.],
            [ 4.,  4.])

where (0, 0) in M' is the sum of (0, 0), (0, 1), (1, 0), (1, 1) in M?

I've found that for-loops are exceedingly slow here.

user1658296
  • 1,398
  • 2
  • 18
  • 46
  • you can use matrix multiplication. take this matrix x = [[1, 1, 0, 0], [0, 0, 1, 1]]. Then M' = x.dot(M.dot(x.T)) – rnbguy Oct 25 '16 at 07:06

1 Answers1

1

Here is a possible solution.

import numpy as np
import itertools

>>> x = np.arange(16).reshape((4,4))
>>> x
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
>>> for i, j in itertools.product([0,2],[0,2]):
...     print np.sum(x[i:i+2,j:j+2])
... 
10
18
42
50
>>> 

Found an elegant solution here.

>>> x.reshape(2,2,2,2).sum(axis=(1,3))
array([[10, 18],
       [42, 50]])
>>> 
Community
  • 1
  • 1
Quazi Marufur Rahman
  • 2,603
  • 5
  • 33
  • 51