Addition and Multiplication of Matrix in Python 3

Addition and Multiplication of Matrix in Python 3

=========

m1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

m2 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
m3 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
m4 = [[1,2,3,4],[4,5,6,7],[7,8,9,0]]
class TwoDimMatrixOp:
def __init__(self, m1, m2):
self._m1 = m1
self._m2 = m2
self._result = [ [0]*(len(m1)-1) for _ in xrange(len(m2)) ]
def sum(self):
# iterate through rows
for i in range(len(self._m1)):
# iterate through columns
for j in range(len(self._m1[i])):
self._result[i][j] = self._m1[i][j] + self._m2[i][j]
for r in self._result:
print(r)
def multi(self):
self._result_mult = [ [0]*(len(m1)) for _ in xrange(len(m2[0])+1) ]
# iterate through rows of X
for i in range(len(self._m1)):
# iterate through columns of Y
for j in range(len(self._m2[0])):
# iterate through rows of Y
for k in range(len(self._m2)):
self._result_mult[i][j] += self._m1[i][k] * self._m2[k][j]
for r in self._result_mult:
print(r)
TwoDimMatrixOp(m1, m2).sum()
TwoDimMatrixOp(m3, m4).multi()

Comments are closed.