Matrices

These notes describe how to define and process a matrix with the Python programming language. One should first be familiar with list iteration before tackling these notes.

A matrix is a rectangular table of elements. The following is a 2x4 matrix, meaning there are 2 rows, 4 columns:

 5     4     7 11
 3 3 8 17

Matrix Representation

In Python and other programming languages, a matrix is often represented with a list of lists. The sample matrix above could be created with:

            matrix = [  [5,4,7,11],[3,3,8,17]  ]

So matrix[0][0] is 5, matrix[0][1] is 4, and so on.

Processing a Matrix

We process a 1-d list with an index variable and a loop. To process a matrix, we use a nested loop, that is, one loop embedded in another. We define two index variables, often called row and col (or i and j). To 'visit' every element, we set the row to 0, then loop through each column. Then we set the row to 1, and loop through that row's columns. We continue, until we've processed each row.

So in the above matrix, we'd visit 5, then 4, then 7, then 11, then switch to the next row and visit 3, then 3, then 8, then 17.

Here's code to actually do this:

            matrix = [  [5,4,7,11],[3,3,8,17]  ]
            row=0
            while row<2:
                col=0
                while col<4:
                    print matrix[row][col]
                    col=col+1
                row=row+1



In-Class Assignment

1. Copy the code in the sample above and get it to run.
2. Change the matrix so that it has only 3 columns, e.g., remove the 11 and 17. Rerun the program. What happens?
3. Fix the program so that it works.
4. Write the code so that the loop processing will work no matter how big the matrix is, i.e., change the code so that if you change the line defining the matrix to any number of rows and columns, the processing will still work.

5. PROGRAMMER MILESTONE: Write a program that will compute the total of all elements of a matrix of any size.


Recent site activity