[Tutor] How to sum rows and columns of a matrix?
Kent Johnson
kent37 at tds.net
Wed Feb 2 13:54:53 CET 2005
Kent Johnson wrote:
> Liam Clarke wrote:
>
>> There's a specific package for arrays
>> http://www.stsci.edu/resources/software_hardware/numarray
>>
>> that implements array mathematics. I use it for pixel map manipulation
>> in pygame, so it's relatively fast.
>
>
> Here is one way to do what you want using numarray:
Here is another way, probably more idiomatic and faster. (I'm just doodling with numarray so there
may still be a better way to do this...)
>>> import numarray
>>> m=numarray.array(range(16),shape=(4,4))
>>> numarray.add.reduce(m)
array([24, 28, 32, 36])
>>> numarray.add.reduce(m, axis=1)
array([ 6, 22, 38, 54])
Kent
>
> >>> import numarray
>
> Create a 4x4 array:
> >>> m=numarray.array(range(16),shape=(4,4))
> >>> m
> array([[ 0, 1, 2, 3],
> [ 4, 5, 6, 7],
> [ 8, 9, 10, 11],
> [12, 13, 14, 15]])
>
> Row access:
> >>> m[1]
> array([4, 5, 6, 7])
>
> Column access:
> >>> m[:,1]
> array([ 1, 5, 9, 13])
>
> Sum all the rows:
> >>> [sum(m[i]) for i in range(4)]
> [6, 22, 38, 54]
>
> Sum all the columns:
> >>> [sum(m[:,i]) for i in range(4)]
> [24, 28, 32, 36]
>
> Kent
>
>>
>>
>> On Mon, 31 Jan 2005 19:09:59 +0100, Gregor Lingl <glingl at aon.at> wrote:
>>
>>> Hi all of you,
>>>
>>> I'm representing a 4x4 matrix as a 16-element list, e.g.
>>>
>>> m=range(16)
>>>
>>> first 4 elements first row, second four elements second row etc.
>>> I want to sum rows and columns like
>>>
>>> i-th row:
>>>
>>> sum(m[4*i:4*i+4])
>>>
>>> and ith column:
>>>
>>> sum(m[i::4])
>>>
>>> This seems to be slow because of the formation of the slices.
>>> I wonder if there is a way using generators or generator-expressions
>>> (which I didn't study yet) to compute these sums without copying
>>> parts of the matrix to a new list. (I'd guess that there should exist
>>> some canonical generator for sequences, which produces their elements
>>> ..., maybe also for slices ?)
>>>
>>> All comments, hints, solutions are welcome.
>>>
>>> Regards,
>>> Gregor
>>>
>>> --
>>> Gregor Lingl
>>> Reisnerstrasse 3/19
>>> A-1030 Wien
>>>
>>> Telefon: +43 1 713 33 98
>>> Mobil: +43 664 140 35 27
>>>
>>> Autor von "Python für Kids"
>>> Website: python4kids.net
>>> _______________________________________________
>>> Tutor maillist - Tutor at python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>
>>
>>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list