【发布时间】:2011-03-16 16:47:28
【问题描述】:
class Matrix:
def __init__(self, data):
self.data = data
def __repr__(self):
return repr(self.data)
def __add__(self, other):
data = []
for j in range(len(self.data)):
for k in range(len(self.data[0])):
data.append([self.data[k] + other.data[k]])
data.append([self.data[j] + other.data[j]])
data = []
return Matrix(data)
x = Matrix([[1,2,3],[2,3,4]])
y = Matrix([[10,10,10],[10,10,10]])
print(x + y,x + x + y)
我能够让矩阵添加 1 行 x n 列,但是当我尝试通过添加第二个循环来改进所有 n x n 矩阵时,我得到了这个错误。
Traceback (most recent call last):
line 24, in <module>
print(x + y,x + x + y)
line 15, in __add__
data.append([self.data[k] + other.data[k]])
IndexError: list index out of range
【问题讨论】:
-
你考虑过使用numpy.matrix吗?
-
@StephenPaulger:我不认为推荐一个关于
numpy的python 新手是个好主意。numpy确实很棒,但是如果您仍然掌握基本的 Python 概念,使用它是 IMO 灾难的秘诀。 -
我明白你的意思,但 Python 的真正优势之一是大多数事情已经由某人完成并且它们很容易重用。任何了解矩阵乘法的人都应该能够弄清楚如何安装和使用 numpy。 :)
标签: python oop class matrix addition