Strict Standards: Declaration of Doku_Renderer_metadata::table_open() should be compatible with Doku_Renderer::table_open(\$maxcols = NULL, \$numrows = NULL, \$pos = NULL) in /home2/cp-wiki/htdocs/inc/parser/metadata.php on line 480

Strict Standards: Declaration of Doku_Renderer_metadata::table_close() should be compatible with Doku_Renderer::table_close(\$pos = NULL) in /home2/cp-wiki/htdocs/inc/parser/metadata.php on line 480

Lab 2 Problem

Matrix multiplication using arrays.

• Read in number n which indicates the dimensions of the matrix.
• Create the matrix array with the zeros function, reading in n^2 numbers from file matrixA.txt.
• After reading in the matrix A, print out A.
• Next, read in n^2 numbers from file matrixB.txt.
• Next, print out matrix B.
• Note: solution below reads row by row and reads files simultaneously
• Then, use matrix multiplication to calculate A*B, and print out the result.

Sample Solution

```#Lab 2, Lab problem 1
#Course solution

def main():
from numpy import zeros
import string

# asking the user to input n is not a good idea in general;
# n can be determined from the first file line and file reading continues until no more input; or the
# first line of the file can contain n
# in lab assignments you can assume that the input data is "nice"

n = input("Input the dimension of the matrices: ")
n = int(n)

fileA = open("matrixA.txt")  # open files as in bird.py
fileB = open("matrixB.txt")

matrixA = zeros((n,n))  # initialize all three arrays with zeros
matrixB = zeros((n,n))
result = zeros((n,n))

# there exist a number of correct ways to read the two matrices; the one belows is
# similar to the bird example from class
for i in range(n):
lineB = fileB.readline()    # as in bird.py; here split is on space
rowA = string.split(lineA, " ")
rowB = string.split(lineB, " ")

for j in range(n):                  # convert elements in the strings to integers
matrixA[i][j] = int(rowA[j])    # assign to individual array entries
matrixB[i][j] = int(rowB[j])

print "A: "
print matrixA
print "B: "
print matrixB

for i in range(n):      # double loop to generate all n^2 entries
for j in range(n):  # one loop to compute each entry
for k in range(n):
result[i][j] += matrixA[i][k] * matrixB[k][j]

print "A*B: "
print result

main()```