Question: Problem 1. Extend the implementation of the Matrix class so that it overloads the +, -, and * operators. class Matrix: def __init__(): #FIXME: Replace

Problem 1.

Extend the implementation of the Matrix class so that it overloads the +, -, and * operators.

class Matrix: def __init__(): #FIXME: Replace with your code pass def __add__(self, other): pass #FIXME: REPLACE WITH IMPLEMENTATION def __sub__(self, other): pass #FIXME: REPLACE WITH IMPLEMENTATION def __mul__(self, other): if type(other) == float: print("FIXME: Insert implementation of MATRIX-SCALAR multiplication") #REPLACE elif type(other) == Matrix: print("FIXME: Insert implementation of MATRIX-MATRIX multiplication") #REPLACE elif type(other) == Vec: print("FIXME: Insert implementation for MATRIX-VECTOR multiplication") #REPLACE else: print("ERROR: Unsupported Type.") return def __rmul__(self, other): if type(other) == float: print("FIXME: Insert implementation of SCALAR-MATRIX multiplication") #REPLACE else: print("ERROR: Unsupported Type.")

"""-----------------------------------TESTER CELL------------------------------------------------""" "TESTING OPERATOR + "

A = Matrix([[1, 2],[3, 4],[5, 6]]) B = Matrix([[1, 2],[1, 2]]) C = Matrix([[10, 20],[30, 40],[50, 60]])

P = A + B # dimension mismatch Q = A + C

print("Matrix A") print(A) print()

print("Matrix C") print(C) print()

print("Matrix Q = A + C") print(Q) print()

"TESTING OPERATOR * " # TESTING SCALAR-MATRIX MULTIPLICATION T = -0.5 * B print("Matrix B") print(B) print()

print("Matrix T = -0.5 * B") print(T) print()

# TESTING MATRIX-MATRIX MULTIPLICATION U = A * B print("Matrix U = A * B") print(U) print()

# TESTING MATRIX-VECTOR MULTIPLICATION x = Vec([0, 1]) # Vec object b = A * x # b is a Vec data type print("Vector b = A * x") print(b)

Output:

ERROR: Dimension mismatch. Matrix A 1 2 3 4 5 6 Matrix C 10 20 30 40 50 60 Matrix Q = A + C 11 22 33 44 55 66 Matrix B 1 2 1 2 Matrix T = -0.5 * B -0.5 -1.0 -0.5 -1.0 Matrix U = A * B 3 6 7 14 11 22 

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!