# [SciPy-User] How Can I Bin A Matrix?

josef.pktd@gmai... josef.pktd@gmai...
Thu Oct 29 11:30:59 CDT 2009

On Thu, Oct 29, 2009 at 12:11 PM, Sebastian Berg
<sebastian@sipsolutions.net> wrote:
> Hi,
>
> I didn't test it much, so I hope its not completely wrong, but I think
> such a thing should do it too with some array reshaping magic, only
> tried with some simple square arrays though:
>
> import numpy as np
>
> def bin(a, n):
>    if np.any(np.array(a.shape) % n != 0):
>        raise ValueError('Clipping not supported')
>    if a.ndim != 2:
>        raise ValueError('Only 2D supported here')
>
>    avg = a.reshape(-1, n).mean(1)
>
>    avg = avg.reshape(-1, n, a.shape[0]/n).mean(1)
>
>    return avg
>
> Regards,
>
> Sebastian
>
> On Thu, 2009-10-29 at 23:09 +0900, David Cournapeau wrote:
>> On Thu, Oct 29, 2009 at 10:58 PM, Joseph Smidt <josephsmidt@gmail.com> wrote:
>> > Hello,
>> >
>> >     Lets pretend I have some random 100x100 matrix and I wanted to
>> > form a 10x10 matrix where each element of the 10x10 matrix is the
>> > average of the corresponding 10x10  block of the 100x100 matrix.
>>
>> you could simply add submatrices for each item of a submatrix. To take
>> your example with 2x2 submatrices:
>>
>> 0.25 * (x[::2,::2] + x[1::2, ::2] + x[::2, 1::2] + x[1::2,1::2])
>>
>> David
>> _______________________________________________
>> SciPy-User mailing list
>> SciPy-User@scipy.org
>> http://mail.scipy.org/mailman/listinfo/scipy-user
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>

maybe with some linear algebra:

>>> a = np.array([( 7, 2, 3, 4 ),
... ( 9, 4, 5, 6 ),
... ( 3, 5, 7, 9 ),
... ( 1, 5, 2, 6 )])
>>> b = np.kron(np.eye(2),np.ones(2))
>>> b
array([[ 1.,  1.,  0.,  0.],
[ 0.,  0.,  1.,  1.]])
>>> np.dot(b,a)
array([[ 16.,   6.,   8.,  10.],
[  4.,  10.,   9.,  15.]])
>>> np.dot(np.dot(b,a),b.T)
array([[ 22.,  18.],
[ 14.,  24.]])
>>>
>>> np.dot(np.dot(b,a),b.T)/(2.**2)
array([[ 5.5,  4.5],
[ 3.5,  6. ]])

Josef