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

Orri Ganel singingxduck at gmail.com
Mon Jan 31 22:48:39 CET 2005


Gregor Lingl 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
>
The way I usually handle this is to have a 2-d array, such that every 
list within the main list is a row:

 >>> m = list(range(4) for i in range(4))
 >>> m
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
 >>> m[0][0] = 1
 >>> m
[[1, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
 >>> m = [range(4) for i in range(4)]
 >>> m
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
 >>> m[0][0] = 1
 >>> m


Either of the above works.  Then, to some a row, you just do this:

 >>> m
[[1, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
 >>> sum(m[0])
7

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.



More information about the Tutor mailing list