2017-08-01 79 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列」其他建議也在做看起來是正確的