[Tutor] matrices

Kirby Urner urnerk@qwest.net
Sun, 7 Apr 2002 11:37:18 -0400


On Sunday 07 April 2002 01:59 pm, Cameron Stoner wrote:
> Hi all,
>
> If you make a compound list like this:
> >>> l = ["1","1","1"]
> >>> ll = ["2","2","2"]
> >>> lll= ["3","3","3"]
> >>> ll = [l,l,l]
> >>> lll = [ll,ll,]
> >>> lll
>
> [[['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']], [['1', '1', '1'],
> ['1', '1', '1'], ['1', '1', '1']]]
>
> are you making a matrix?
>
> Cameron

This looks more complicated than you'd need for an ordinary
two-dimensional matrix (same as 2D array).  For example, a 
math book might have the following matrix:

         1  3  5
        -1  0  0
        -2  1  0

If you wanted that in a 2D array, you could just go:

matrix = [[1, 3, 5],[-1,0,0],[-2,1,0]]

A difference from math texts is they usually use 1-based
indexing, i.e. upper left entry is row 1, column 1, whereas
in Python (and many other computer languages), zero-based
indexing is the norm.  So we get:

 >>> matrix[0][0]
 1
 >>> matrix[1][1]
 0

and so on.

However, a more typical implementation of a matrix in 
Python would be as a class definition, with operator 
overriding used to endow the instances with the powers
matrices usually have, such as the power to multiply,
add, subtract, invert (if square).  

I've done such a matrix implementation, with the square 
matrix (having even more powers, such as determinant) 
a subclass of the more generic rectangular matrix.  I can 
point you to a website with the source code if you're 
interested.

I think you'll find many implementations of the matrix 
concept in Python, saved in the various stashes.  And 
then, of course, there's Numeric, or NumPy, which 
implements an indigenous from of n-dimensional array, 
with fancier ways of slicing and dicing them, along with 
a whole linear algebra package.  But that's overkill in
some contexts (plus less instructive than rolling one's
own).

Kirby