2021年3月6日星期六

How to sum two matrix in a class

I'm trying to define some methods to a class Matrix that receives the number of rows and the number of columns, a list or a code as arguments. I have to do:

import numpy as np    class Matrix:        def __init__(self, rows = 0, columns =0, data=None, code =''):          if data is None:              data = []          self.code = ''          self.rows = rows          self.columns = columns          self.data = data          self.code = code          self.matrix = [[]]          assert self.columns != 0 and self.rows != 0          if code == 'z':              self.matrix = np.zeros([self.rows, self.columns], int)          elif code == 'u':              self.matrix = np.ones([self.rows, self.columns], int)          elif code == 'i':              self.matrix = np.identity(self.rows, int)          else:              if code == '' and len(self.data) != 0:                  self.matrix = np.reshape(self.data, (-1, self.columns))        def __str__(self):          return f'Matrix: {self.matrix}'        def get_matrix(self):          return self.matrix        def sumM(self,m1):          k = self.get_matrix()          m1.get_matrix()          print(k)          print(m1.get_matrix())          assert (self.rows == m1.rows)          m3 = np.zeros([self.rows, self.rows])          print(m3.shape)          for i in range(m3.shape[0]):                for j in range(m3.shape[1]):                    output = m1[i, j] + k[i, j]              print(output)          return m3  

Although, when I'm call the sumM method, python retrieves the error:

Traceback (most recent call last):    File "<input>", line 1, in <module>    File "C:/Users/sandr/PycharmProjects/Trabalho 2/teste2.py", line 41, in sumM      output = m1[i, j] + k[i, j]  TypeError: 'Matrix' object is not subscriptable  

What I'm doing wrong?

https://stackoverflow.com/questions/66512201/how-to-sum-two-matrix-in-a-class March 07, 2021 at 08:52AM

没有评论:

发表评论