【问题标题】:Matrix multiplication explanation矩阵乘法解释
【发布时间】:2017-08-01 16:07:32
【问题描述】:

当我们将两个大小为 m x k 的矩阵 A 和大小为 k x n 的 B 相乘时,我们使用以下代码:

  #for resultant matrix rows
  for i in range(m):
    #for resultant matrix column
    for j in range(n):
      for l in range(k):
        #A's row x B's columns
        c[i][j]=c[i][j]+a[i][l]*b[l][j]

我的 cmets 在代码中对循环的解释是否正确?是否有更好的循环解释或编码矩阵乘法的更好思考过程?

EDIT1:我不是在寻找更好的代码。我的问题是关于当我们将矩阵乘法的数学转换为代码时的思考过程。

【问题讨论】:

  • 如果您想对评论提出其他建议,那么“A 的第 i 行 x B 的第 j 列”?
  • 另外你可能不应该使用l作为迭代变量,乍一看它看起来像1I
  • 您的代码是正确的。我正在为我的一个项目使用类似的循环(查看此页面上的 javascript:math.tools/calculator/matrix/multiplication)。我很想在页面上添加您要求的详细解释。下面的一些解释很不错,但我仍然觉得我们可以做得更好。

标签: python algorithm matrix matrix-multiplication


【解决方案1】:

您的代码是正确的,但如果您想按照您的要求添加详细的注释/解释,您可以这样做:

 #for resultant matrix rows
  for i in range(m):
    #for resultant matrix column
    for j in range(n):
      #for each entry in resultant matrix we have k entries to sum
      for l in range(k):
        #where each i, j entry in the result matrix is given by multiplying the 
        #entries A[i][l] (across row i of A) by the entries B[l][j] (down 
        #column j of B), for l = 1, 2, ..., k, and summing the results over l:
        c[i][j]=c[i][j]+a[i][l]*b[l][j]

编辑:如果您想要更好地解释循环或思考过程而不是取出#A's row x B's columns cmets。并将其替换为“结果矩阵中的每个 i, j 条目是通过将条目 A[i][l](在 A 的第 i 行)乘以条目 B[l][j](在B),对于 l = 1, 2, ..., k,并将结果求和到 " 也不要使用 l 作为迭代器,它看起来像 1

【讨论】:

    【解决方案2】:

    您可以使用numpy.dot 函数。这是documentation。示例(摘自文档):

    > a = [[1, 0], [0, 1]]
    > b = [[4, 1], [2, 2]]
    > np.dot(a, b)
    > array([[4, 1],
            [2, 2]])
    

    【讨论】:

    • 文档说明:两个数组的点积。对于二维数组,它相当于矩阵乘法...
    • 对不起,我的错误,无论如何,问题是关于他或她的代码的文档,而不是寻找现有的实现。
    【解决方案3】:

    为了进行 2 个矩阵相乘,应始终保持的条件是第一个 matrix 必须与另一个 matrix 具有相同数量的 rows 具有 columns

    所以如果matrix_1m x n,那么第二个matrix_2 应该是n x p。两者的结果将有一个维度m x p

    Pseudocode 将是:

    multiplyMatrix(matrix1, matrix2)
    
    -- Multiplies rows and columns and sums them
      multiplyRowAndColumn(row, column) returns number
      var
        total: number
      begin
        for each rval in row and cval in column
        begin
           total += rval*cval
        end
        return total
      end
    
    begin
    
    -- If the rows don't match up then the function fails
    
      if matrix1:n != matrix2:m  return failure;
    
      dim    = matrix1:n   -- Could also be matrix2:m
      newmat = new squarematrix(dim)  -- Create a new dim x dim matrix
      for each r in matrix1:rows and c in matrix2:columns
      begin
    
      end
    end
    

    在 python 中,您可以执行您所做的操作,也可以使用ijk-algoikj-algopsyco ikj-algoNumpySciPy 来完成此操作。看来 Numpy 是最快和最有效的。

    您的代码看起来正确,您的评论也看起来正确

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 2015-08-22
      • 2018-04-11
      • 2017-03-11
      • 2013-12-23
      • 2014-09-19
      相关资源
      最近更新 更多