2015-05-04 150 views
-2

为了使函数乘以矩阵,我的代码只打印第一个矩阵的第一个值,并用零填充所有其他位置。下面是具有不同功能的类以及它下面的乘法矩阵函数。异常处理工作和打印功能也起作用。唯一的问题出现矩阵类计算器Python

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 
+5

你忘了说什么了 –

+0

我忘了什么了? – astorinoa

+2

你的问题说“唯一的问题出现”,然后就切断了。他指出,你忘了告诉我们是什么问题,通过做同样的事情。 – abarnert

回答

0

我认为你的问题是在你的“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.

顺便说一句,您可能想考虑的一件事是将此乘法矩阵函数包含在你的Matrix类。如果当您创建矩阵类的两个实例使用这个签名

def __mul__(self): 
    "Your code here" 

再定义一个类的函数,调用它们A和B,那么你就可以在程序中只需键入A * B它们相乘。

+0

非常感谢! – astorinoa

0

您似乎有两个缩进错误,以致您的MultiplyMatrices将无法​​正常工作。下面是更正后的代码:

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

+0

这段代码是为那些没有教过Numpy的类编写的,所以不幸的是我没有被允许使用它。感谢您的帮助!!! – astorinoa