# [Numpy-discussion] subsampling array without loops

Anne Archibald peridot.faceted@gmail....
Mon Aug 25 22:03:53 CDT 2008

```2008/8/22 Catherine Moroney <Catherine.M.Moroney@jpl.nasa.gov>:
> I'm looking for a way to acccomplish the following task without lots
> of loops involved, which are really slowing down my code.
>
> I have a 128x512 array which I want to break down into 2x2 squares.
> Then, for each 2x2 square I want to do some simple calculations
> such as finding the maximum value, which I then store in a 64x256
> array.

You should be able to do some of this with reshape and transpose:
In [1]: import numpy as np

In [3]: A = np.zeros((128,512))

In [4]: B = np.reshape(A,(64,2,256,2))

In [5]: C = np.transpose(B,(0,2,1,3))

In [6]: C.shape
Out[6]: (64, 256, 2, 2)

Now C[i,j] is the 2 by 2 array
[ [A[2*i,2*j], A[2*i,2*j+1]],
[A[2*i+1,2*j], A[2*i+1, 2*j+1]] ]
(or maybe I got those indices the wrong way around.)

Now most operations you want to do on the two-by-two matrices can be
done, using ufuncs, on the whole array at once. For example if you
wanted the max of each two-by-two matrix, you'd write:

In [7]: D = np.amax(np.amax(C,axis=-1),axis=-1)

In [8]: D.shape
Out[8]: (64, 256)

Anne
```