Function name : matrixMultiplication
Parameters : aMatrix (list), bMatrix (list)
Returns Type: list of tuples
Description : Write a function in PYTHON that takes in two matrices (list of tuples or list of lists) and
multiplies the two matrices together. Assume that the given matrices will be valid, i.e.
aMatrix will be n x m (n rows and m columns) and bMatrix will be m x ℓ (m rows and
ℓ columns).
*Assume elements of aMatrix & bMatrix will be numeric values and aMatrix &
bMatrix will be a valid matrix
Test Cases:
>>> matrixMultiplication( [(1,2),(3,4)] , [(-1,0),(0,1)] )
[(-1, 2), (-3, 4)]
>>> matrixMultiplication( [(1,2),(3,4),(5,6)] , [(-1,-1,0),(0,1,1)] )
[(-1, 1, 2), (-3, 1, 4), (-5, 1, 6)]
Please find the answer below, all the details are mentioned in the comments and code snippet of the python code is also attached.
Matrix_Multiplication.py
def matrixMultiplication(aMatrix, bMatrix):
#create a result matrix based on the mxn and nxk = mxk
result = []
for i in range(len(aMatrix)):
list_0 = []
for j in range(len(bMatrix[0])):
list_0.append(0)
result.append(list_0)
# iterate through rows of aMatrix
for i in range(len(aMatrix)):
# iterate through columns of bMatrix
for j in range(len(bMatrix[0])):
# iterate through rows of bMatrix
for k in range(len(bMatrix)):
#print(aMatrix[i], aMatrix[k], bMatrix[k], bMatrix[j])
result[i][j] += aMatrix[i][k] * bMatrix[k][j]
#to convert internal lists to tuple
answer = []
for i in range(len(result)):
x = tuple(result[i])
answer.append(x)
print(answer)
matrixMultiplication( [(1,2),(3,4)] , [(-1,0),(0,1)] )
matrixMultiplication( [(1,2),(3,4),(5,6)] , [(-1,-1,0),(0,1,1)]
)
Output (code snippet and output):
Please let us know in the comments if there is any problem.
1 def matrixMultiplication (aMatrix, bMatrix): 2 #create a result matrix based on the mxn and nxk = mxk [] for i in range(len(aMatrix)): list_e for j in range(len(bMatrix [0] )): list_0.append (0) result.append ( list_0) 4 result [] 6 = 7 10 # iterate through rows of aMatrix for i in range(len(aMatrix)): # iterate through columns of bMatrix for j in range(len(bMatrix[0])): # iterate through rows of bMatrix for k in range (len(bMatrix)) 11 12 13 14 15 16 #print(aMatrix[i], aMatrix[k], bMatrix[k], bMatrix[j]) 17 bMatrix[k][j] += aMatrix[i][k] result[i][j] 18 print(result 19 20 21 matrixMultiplication( [(1,2), (3,4)] , [( -1,0),(0,1)] )] 22 matrixMultiplication( [(1,2),(3,4), (5,6)] , [(-1,-1,0), (0,1,1)] ) [-1, 2], -3, 4]] [I-1, 1, 21, [-3, 1, 4], [-5, 1, 6]]
Get Answers For Free
Most questions answered within 1 hours.