In: Computer Science
Matrix multiplication with arrays
In this question you will verify that the numpy.ndarray matrix multiplication operator, @, does a proper matrix multiplcation. To do this, first write a function, mat_mult(a1, a2) that creates a new 2d array of zeros, and using nested for loops, fill in the elements of the matrix multiplication, and return this new array.
Then, write a second function, matrix_diff(b, c) that takes two arrays as arguments then generates and returns the following ratio:
sqrt((∑(??,?−??,?)^2)/(∑(??,?+??,?)^2))
This function gives a measure of how different two arrays are, giving 0 if the arrays are identical.
Your functions can assume that both matrix arguments are two-dimensional, but they should check that the shapes are compatible and return None if they are not.
Dear Learner,
Here is the solution to your code,
CODE:
import numpy as np
def mat_mult(matrix1,matrix2):
result = [[0 for x in range(len(matrix1))] for y in
range(len(matrix2[0]))] #initializing the result array
for i in range(0,len(matrix1)):
for j in
range(0,len(matrix2[0])):
for k in
range(0,len(matrix2)):
result[i][j] += matrix1[i][k] *
matrix2[k][j]
for r in result:
print(r)
def matrix_diff(matrix1,matrix2):
result=0
numrows1 = len(matrix1) # number of rows in matrix
1
numcols1 = len(matrix1[0]) # number of columns in
matrix 1
numrows2 = len(matrix2) # number of rows in matrix
2
numcols2 = len(matrix2[0]) # number of columns in
matrix 2
if(numrows1 == numrows2) and (numcols1 == numcols2)
:
for i in range (0,numrows1):
for j in
range(0,numcols1):
result += ((matrix1[i][j] -
matrix2[i][j])**2)/((matrix1[i][j] + matrix2[i][j])**2)
else:
print("Error")
print(result)
matrix1 = [[1,2],[3,4]]
matrix2 = [[1,2],[3,4]]
mat_mult(matrix1,matrix2) #call to multiply the 2 matrices
a = np.matrix(matrix1)
b = np.matrix(matrix2)
print(a@b) #numpy operator
matrix_diff(matrix1,matrix2) #call to the function to calculate
difference
SCREENSHOT:
OUTPUT:
I hope I have answered the question the way you were expecting. If you still have any doubts or want any other explanation or modification, feel free to ask us in the comments.
Please leave a like if this was helpful.
Thanks,
Happy Studying.