Programming Assignment #3

Matrix Multiplication in Python

The Program:

This assignment output is identical to Program 2 in C. For this assignment, you will multiply two matrices

and print the result. If A is an m x n matrix, and B is an n x p matrix, then the product matrix C, which is A

x B, is defined to be the m x p matrix whose entry in the ith row and the jth column is the sum of the

products of corresponding entries of the ith row of A and the jth column of B. A standard algorithm is:

for(int i=0; i < m; i++)

for(int j=0; j < p; j++) {

C[i][j] = 0;

for(int k=0; k < n; k++)

C[i][j] += A[i][k] * B[k][j];

}

Input:

will take the following form. The first three lines of the file contain the values m, n, and p, each on a line

by themselves. Following are two matrices, A followed by B with no blank lines, of the dimensions

specified, one row per line. Each row entry is separated by a space. Example: Given the following two

matrices A and B:

A = |1 2| B = |3|

|4|

The datafile will then have this format:

1

2

1

1 2

3

4

sys library:

For this assignment, the only library you may is sys. (Python has a built-in array module, which you may

not use. Instead, the matrices will be lists which are very similar to arrays.) Immediately following the

header comment section at the top of your program, add the line:

import sys

Output:

As usual, your program will first print a title line, consisting of the assignment number, your class account,

and your name, all on one line. Then your program will print the two matrices to be multiplied, and finally

print the resulting matrix (pretty formatting is appreciated, but not necessary). Each of the three matrices

should be labeled. Example:

Program #3, csscxxxx, Student Name

Matrix A contents:

1 2

3 4

5 6

Matrix B contents:

7 8 9 10

11 12 13 14

Matrix A * B is:

29 32 35 38

65 72 79 86

101 112 123 134

The datafile read for this example is:

3

2

4

1 2

3 4

5 6

7 8 9 10

11 12 13 14

Additional Requirements:

· You may use brackets [ ] in your code.

· The matrices A and B must be declared as empty lists: A = [] and B = []

· No error checking of input data file content is required for this assignment. You may assume that

any datafile used for testing will contain only integer values in the format specified in the

assignment.

· Your source code file will be run on edoras, using the command:

python3 p3.py datafileName

· Your p3.py program file must contain exactly four functions, whose prototypes are:

– main()

– read_matrices(A,B) which returns matrix C

– mult_matrices(A,B,C)

– print_matrix(arr)