In [51]:
def multiplyMatrices(a, b):
# Get the number of rows which also happens to be the number of columns
# Assuming we're dealing with square n x n matrices
n = len(a)
# Create a new matrix to store the result
Matrix = [[0 for x in range(n)] for y in range(n)]
# compute the values of each row in the new matrix i
for i in range(n):
# compute the values of each column ij of the new matrix
for j in range(n):
# initialize the new value to 0
Matrix[i][j] = 0
# add the previously calculated value to the product of column k of a and row j of b
for k in range(n):
Matrix[i][j] = Matrix[i][j] + a[i][k] * b[k][j]
return Matrix
In [49]:
def printMatrix(msg, a):
n = len(a)
print (msg)
for x in range(n):
for y in range(n):
print (a[x][y], end=' ')
print()
In [48]:
def getDummy2x2MatrixA():
a = [[0 for x in range(2)] for y in range(2)]
a[0][0] = 2
a[1][0] = 5
a[0][1] = 1
a[1][1] = 2
return a
def getDummy2x2MatrixB():
b = [[0 for x in range(2)] for y in range(2)]
b[0][0] = 1
b[1][0] = 3
b[0][1] = 4
b[1][1] = 6
return b
In [52]:
a = getDummy2x2MatrixA()
b = getDummy2x2MatrixB()
result = multiplyMatrices(a, b)
printMatrix("A", a)
printMatrix("B", b)
printMatrix("Result", result)