将两个矩阵相加(使用方法,不使用 numpy)
adding two matrices together (using methods, without using numpy)
如何使用实现的方法添加矩阵?
我的问题是我不是很清楚怎样才能得到正确添加矩阵的操作。
比如这样的操作:
A = 1 2 3 1 2 1
4 5 6 + 0 1 0
7 8 9 3 2 1
我想使用 Matrix 中的方法 class:
class Matrix:
def __init__(self, m, n, init=True):
if init:
self.rows = [[0] * n for x in range(m)]
else:
self.rows = []
self.m = m
self.n = n
def __getitem__(self, idx):
return self.rows[idx]
def __setitem__(self, idx, item):
self.rows[idx] = item
def __add__(self, mat):
ret = Matrix(self.m, self.n)
for x in range(self.m):
row = [sum(item) for item in zip(self.rows[x], mat[x])]
ret[x] = row
return ret
为我更新了以下运行,尽管还有改进的余地(检查矩阵大小,...)
def getitem(self, idx):
return self.rows[idx]
def setitem(self, idx, item):
self.rows[idx] = item
def add(self, mat):
ret = Matrix(self.m, self.n)
for x in range(self.m):
row = [sum(item) for item in zip(self.rows[x], mat.getitem(x))]
ret.setitem(x,row)
return ret
mat_a = Matrix(5,5)
mat_b = Matrix(5,5)
mat_b.setitem(slice(0,3),[[1,2,3,4,5],[4,5,6,7,8],[9,10,4,3,1]])
mat_c = mat_a.add(mat_b)
print(mat_c.getitem(slice(0,3)))
如何使用实现的方法添加矩阵?
我的问题是我不是很清楚怎样才能得到正确添加矩阵的操作。
比如这样的操作:
A = 1 2 3 1 2 1
4 5 6 + 0 1 0
7 8 9 3 2 1
我想使用 Matrix 中的方法 class:
class Matrix:
def __init__(self, m, n, init=True):
if init:
self.rows = [[0] * n for x in range(m)]
else:
self.rows = []
self.m = m
self.n = n
def __getitem__(self, idx):
return self.rows[idx]
def __setitem__(self, idx, item):
self.rows[idx] = item
def __add__(self, mat):
ret = Matrix(self.m, self.n)
for x in range(self.m):
row = [sum(item) for item in zip(self.rows[x], mat[x])]
ret[x] = row
return ret
为我更新了以下运行,尽管还有改进的余地(检查矩阵大小,...)
def getitem(self, idx):
return self.rows[idx]
def setitem(self, idx, item):
self.rows[idx] = item
def add(self, mat):
ret = Matrix(self.m, self.n)
for x in range(self.m):
row = [sum(item) for item in zip(self.rows[x], mat.getitem(x))]
ret.setitem(x,row)
return ret
mat_a = Matrix(5,5)
mat_b = Matrix(5,5)
mat_b.setitem(slice(0,3),[[1,2,3,4,5],[4,5,6,7,8],[9,10,4,3,1]])
mat_c = mat_a.add(mat_b)
print(mat_c.getitem(slice(0,3)))