-1

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
rdmtinez
  • 83
  • 2
  • 11
  • `self.matrix_add` instead `matrix_add` in `__add__` function. – ᴀʀᴍᴀɴ Jan 19 '17 at 10:36
  • And even when i write: return self.matrix_add(a, b) I get another error message object of type Matrix has no len() – rdmtinez Jan 19 '17 at 10:39
  • You don't need pass `a` as a parameter to `matirx_add` , just use it as class attribute , `a.self` instead `a` – ᴀʀᴍᴀɴ Jan 19 '17 at 10:42
  • @RicardoMartinez: sure, there can be *other* errors too, but the error posted *in your question* is caused by the lack of using `self`. – Martijn Pieters Jan 19 '17 at 10:43
  • @RicardoMartinez: you are calling `len()` on a `Matrix` instance. You didn't provide a `__len__` method, so that *also* breaks. – Martijn Pieters Jan 19 '17 at 10:44
  • @Arman, that solved that issue, thanks a lot, but now I can't seem to get the len() function working properly – rdmtinez Jan 19 '17 at 10:45
  • see Martijin comments , as he said there is no `__len__` method for `Matrix` instance. – ᴀʀᴍᴀɴ Jan 19 '17 at 10:46
  • I get that, but I don't see why it matters, shouldn't it just use the regular len to find the length of a matrix, or how do i make it so that len() is called on the matrix that is the object, rather than the object itself? – rdmtinez Jan 19 '17 at 10:48

2 Answers2

0

You have to indent all lines except the first, precede the matrix_add function call with self (as @Arman said) and implement a __len__(self) function:

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 self.matrix_add(self.a, b)

    def __len__(self):
        # TODO: FILL THIS IN
        pass

    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)]

After this, you are also going to get another error, asking for yet another function which you have to implement. Google it, and good luck ;-)

vages
  • 330
  • 1
  • 6
  • 14
0

just send the list directly to the matrix

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 self.matrix_add(self.a, b.a)

        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)]

    A = Matrix([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
    B = Matrix([[2, 3, 4], [2, 3, 4], [2, 3, 4]])
    print(A+B)
Smart Manoj
  • 5,230
  • 4
  • 34
  • 59