[Numpy-discussion] block matrix and sums of blocks

Xavier Gnata xavier.gnata@gmail....
Mon Feb 23 14:06:06 CST 2009


Robert Kern wrote:
> On Sun, Feb 22, 2009 at 19:39, Xavier Gnata <xavier.gnata@gmail.com> wrote:
>   
>> Hi,
>>
>> Let us consider one kN x kM array.
>> What is the fastest way to sum each k x k square block of A and to put
>> all these results into a NxM array B?
>>
>> For instance:
>> If A =
>> [112233
>>  112233
>>  223311
>>  223311]
>> then B =
>> [4 8 12
>>  4 12 4]
>>
>> No sanity checks on the arrays shapes are requiered. Only speed matters ;)
>>     
>
> In [6]: A
> Out[6]:
> array([[1, 1, 2, 2, 3, 3],
>        [1, 1, 2, 2, 3, 3],
>        [2, 2, 3, 3, 1, 1],
>        [2, 2, 3, 3, 1, 1]])
>
> In [7]: k = 2
>
> In [8]: add.reduceat(add.reduceat(A, arange(0, A.shape[0], k),
> axis=0), arange(0, A.shape[1], k), axis=1)
> Out[8]:
> array([[ 4,  8, 12],
>        [ 8, 12,  4]])
>
>   
It does the job and I have learned .reduceat :)

Thanks,
Xavier


More information about the Numpy-discussion mailing list