矩阵类计算器Python

时间:2015-05-04 03:45:22

标签: 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

2 个答案:

答案 0 :(得分: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

编写内容的方式,代码将在仅计算第一个条目值后返回Result矩阵。我假设您将其他值默认为0,这可以解释为什么结果矩阵中的其余条目打印为0。

顺便提一下,您可能要考虑的一件事是在Matrix类中包含此乘法矩阵函数。如果使用此签名定义类函数

def __mul__(self):
   "Your code here"

然后当您创建矩阵类的两个实例时,将它们称为A和B,然后只需键入A * B就可以在程序中将它们相乘。

答案 1 :(得分: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的矩阵。