矩阵类计算器Python
在生成矩阵相乘的函数时,我的代码只打印第一个矩阵的第一个值,并用零填充所有其他位置。下面是具有不同函数的类及其下面的乘法矩阵函数。异常处理工作正常,打印功能也工作正常。唯一的问题是矩阵类计算器Python,python,Python,在生成矩阵相乘的函数时,我的代码只打印第一个矩阵的第一个值,并用零填充所有其他位置。下面是具有不同函数的类及其下面的乘法矩阵函数。异常处理工作正常,打印功能也工作正常。唯一的问题是 class Matrix(object): """Input the dimensions of your matrix""" def __init__(self, rows = 3, cols = 3): self.rows = rows self.cols = cols
class Matrix(object):
"""Input the dimensions of your matrix"""
def __init__(self, rows = 3, cols = 3):
self.rows = rows
self.cols = cols
self.rowList = [ [0 * x for x in range(cols)] for count in range(rows)]
def setRow(self, index = 0, RowData = [0]*2):
"""Enter the index of the row you are defining followed by a string with the values seperated by commas"""
i = 0
if index >= self.cols:
print("Index is out of the bounds that you defined earlier")
return None
if len(RowData) != self.cols:
print("The Row length exceeds the column size of this matrix")
return None
else:
self.rowList[index] = RowData
def rowCount(self):
return self.rows
def columnCount(self):
return self.cols
def get(self, row, col):
return self.rowList[row][col]
def set(self, value = 0, row = 0, col = 0):
self.rowList[row][col] = value
return None
def MultiplyMatrices(A = Matrix(), B = Matrix()):
ARows = A.rowCount()
ACols = A.columnCount()
BRows = B.rowCount()
BCols = B.columnCount()
if ACols != BRows:
print("Matrices are incompatible, therefore cannot be multiplied")
return None
Result = Matrix(ARows, BCols)
for A_row in range(ARows):
for B_col in range(BCols):
Res = 0
for B_row in range(BRows):
Res = Res + A.get(A_row, B_row) * B.get(B_row, B_col)
Result.set(Res, A_row, B_col)
return Result
我认为你的问题在你的“for”循环中 你有
for B_row in range(BRows):
Res = Res + A.get(A_row, B_row) * B.get(B_row, B_col)
Result.set(Res, A_row, B_col)
return Result
但应该是这样
for A_row in range(ARows):
for B_col in range(BCols):
Res = 0
for B_row in range(BRows):
Res = Res + A.get(A_row, B_row) * B.get(B_row, B_col)
Result.set(Res, A_row, B_col)
return Result
按照您编写的方式,您的代码将在只计算第一个输入值之后返回结果矩阵。我假设其他值默认为0,这可以解释为什么结果矩阵中的其余条目打印为0
顺便说一下,你可能要考虑的一件事是在矩阵类中包含这个多重矩阵函数。如果使用此签名定义类函数
def __mul__(self):
"Your code here"
然后,当您创建matrix类的两个实例时,将它们称为A和B,然后您可以通过键入A*B在程序中对它们进行乘法。您似乎有两个缩进错误,因此您的
多重矩阵将无法正常工作。以下是更正后的代码:
for A_row in range(ARows):
for B_col in range(BCols):
Res = 0
for B_row in range(BRows):
Res = Res + A.get(A_row, B_row) * B.get(B_row, B_col)
Result.set(Res, A_row, B_col) # this edited so it's the sum over B_row
return Result # this set so it's after all three loops have completed
顺便说一句,我看不出默认值(a=Matrix(),B=Matrix())
对您有什么好处。如果您没有得到所需的输入,那么最好只引发一个异常,而不是静默地返回一个全零矩阵
另外,如果您还没有意识到,您应该知道Python中有一套用于处理矩阵的高级工具,名为。您忘了说什么了,我忘了说什么了?您的问题是“唯一的问题是”然后就中断了。他指出你忘了告诉我们问题是什么,因为你做了完全相同的事情。这段代码是为一个没有教Numpy的班级编写的,很不幸,我不被允许使用它。谢谢你的帮助!!!