2017-08-01 81 views
0

当我们乘大小米×k的两个矩阵A和大小k x的B n的我们用下面的代码:矩阵乘法解释

#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] 

是我在循环的代码正确解释意见?有更好的循环解释还是有更好的思维过程来编码矩阵乘法?

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

+1

? – DVT

+0

你也许不应该使用'l'作为迭代变量,它看起来像是'1'或'I' – user3080953

回答

0

您可以使用numpy.dot函数。这是documentation。示例(从documentatio提取):

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

该文档指出: _Dot两个数组的产物。对于二维阵列,它相当于矩阵乘法......_ –

+0

对不起,我的错误无论如何,问题都是关于他或她的代码的文档,而不是寻找现有的实现。 – dashiell

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评论。并将其替换为“其中结果矩阵中的每个i,j条目是通过将条目A [i] [1](在A的第i行上)乘以条目B [1] [j] B),对于l = 1,2,...,k,并且将结果相加在“也不使用l作为迭代器时,它看起来像1

0

应该始终站得住脚的条件2矩阵乘法是,第一个matrix必须具有相同数量的rows,即其他matrix具有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 

在蟒蛇要么你可以做你做了什么,或者你可以使用ijk-algoikj-algopsyco ikj-algoNumpy,或SciPy来完成此操作。看起来Numpy是最快和最有效的。

你的代码看起来正确和评论,如果你想的评论,然后在“A的第i行X B的第j列”其他建议也在做看起来是正确的