[Tutor] How to sum rows and columns of a matrix?

Liam Clarke cyresse at gmail.com
Mon Jan 31 19:39:10 CET 2005


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.


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
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


More information about the Tutor mailing list