I am doing an assignment for a programming class where I am required to overload the standard operators (+, *, -) and have them work with Matrix class objects. I think I am doing it properly but Python keeps spitting out a name error and I have no Idea why, since the function is defined.
I have tried many things, but I still keep coming back to my original code (below). Please help
class Matrix:
"""A Class Matrix which can implement addition, subtraction and multiplication
of two matrices; scalar multiplication; and inversion, transposition and
determinant of the matrix itself"""
def __init__(self, a):
"""Constructor for the Class Matrix"""
#what if you only want to work with one matrix
self.a = a
def __add__(self, b):
return matrix_add(self.a, b)
def matrix_add(self, a, b):
"""
Add two matrices.
Matrices are represented as nested lists, saved row-major.
>>> matrix_add([[1,1],[2,2]], [[0,-2],[3,9]])
[[1, -1], [5, 11]]
>>> matrix_add([[2,3],[5,7]], [[11,13],[17,19]])
[[13, 16], [22, 26]]
>>> matrix_add([[2,3,4],[5,7,4]], [[11,13,1],[17,19,1]])
[[13, 16, 5], [22, 26, 5]]
>>> matrix_add([[1,2],[3,4]],[[1,2]])
Traceback (most recent call last):
...
MatrixException: matrices must have equal dimensions
"""
rows = len(a) # number of rows
cols = len(a[0]) # number of cols
if rows != len(b) or cols != len(b[0]):
raise MatrixException("matrices must have equal dimensions")
return [[a[i][j] + b[i][j] for j in range(cols)] for i in range(rows)]
I'm calling it using the following:
A = Matrix([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
B = Matrix([[2, 3, 4], [2, 3, 4], [2, 3, 4]])
And i get this error message:
----------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-113-74230a6e5fb2> in <module>()
----> 1 C = A + B
<ipython-input-110-e27f8d893b4d> in __add__(self, b)
22 def __add__(self, b):
23
---> 24 return matrix_add(self.a, b)
25
NameError: name 'matrix_add' is not defined