Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Matrix:
- def __init__(self, data): #takes in a double array no matter the size of it.
- self.data = data
- self.rows = len(data) #determines row by number of items in list
- self.cols = len(data[0]) #determines columns by number of items withing list of a list
- self.size = [self.rows, self.cols] #determines how big the matrix is by number of rows and columns
- def multiply(self, other):
- if self.cols == other.rows: #number of columns in first matrix should be same as number of rows on 2nd matric
- result = [[0 for i in range(other.cols)] for i in range(self.rows)] #number of rows as 1st matrix + number of columns of 2nd matrix
- #print(result)
- #iterate by rows of first matrix
- for i in range(self.rows):
- # iterating by columns of second matrix
- for j in range(other.cols):
- # iterating by rows of second matrix
- for k in range(other.rows):
- result[i][j] += self.data[i][k] * other.data[k][j]
- return result
- else:
- return "cant be multiplied"
- def add(self, other): #works good
- if self.size == other.size:
- result = result = [[0 for i in range(self.cols)] for i in range(self.rows)]
- for i in range(self.rows):
- # iterate through columns
- for j in range(other.cols):
- result[i][j] = self.data[i][j] + other.data[i][j]
- return result
- else:
- return " can't be added, dimensions are not equal"
- def subtract(self, other):
- if self.size == other.size:
- result = result = [[0 for i in range(self.cols)] for i in range(self.rows)]
- for i in range(self.rows):
- # iterate through columns
- for j in range(other.cols):
- result[i][j] = self.data[i][j] - other.data[i][j]
- return result
- else:
- return " can't be subtracted, dimensions are not equal"
- def scalar_multi(self, number):
- self.data = [[i * number for i in sublist] for sublist in self.data] #returns scalar multiplication
- return self.data
- # for x in range(self.cols):
- # i[x] = i[x]*number
- # return self.data
- def print_matrix(self):
- for i in self.data:
- print(*i)
- def get_data(self):
- return self.data
- def transpose(self):
- trans= [list(i) for i in zip(*self.data)]
- return trans
- # def mean(self):
- # lst = self.data
- # result = [sum(x) for x in zip(*lst)]
- # for i, v in enumerate(result):
- # result[i] = v /len(lst)
- # return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement