Matrix multiplication: Difference between revisions
Content added Content deleted
(→Go: New section) |
(→{{header|Prolog}}: Added PureBasic) |
||
Line 985: | Line 985: | ||
mmult(M1, M2, M3) :- transpose(M2,MT), maplist(mm_helper(MT), M1, M3). |
mmult(M1, M2, M3) :- transpose(M2,MT), maplist(mm_helper(MT), M1, M3). |
||
mm_helper(M2, I1, M3) :- maplist(dot(I1), M2, M3).</lang> |
mm_helper(M2, I1, M3) :- maplist(dot(I1), M2, M3).</lang> |
||
=={{header|PureBasic}}== |
|||
Matrices represented as integer arrays with rows in the first dimension and columns in the second. |
|||
<lang PureBasic>Procedure multiplyMatrix(Array a(2), Array b(2), Array prd(2)) |
|||
Protected ar = ArraySize(a()) ;#rows for matrix a |
|||
Protected ac = ArraySize(a(), 2) ;#cols for matrix a |
|||
Protected br = ArraySize(b()) ;#rows for matrix b |
|||
Protected bc = ArraySize(b(), 2) ;#cols for matrix b |
|||
If ac = br |
|||
Dim prd(ar, bc) |
|||
Protected i, j, k |
|||
For i = 0 To ar |
|||
For j = 0 To bc |
|||
For k = 0 To br ;ac |
|||
prd(i, j) = prd(i, j) + (a(i, k) * b(k, j)) |
|||
Next |
|||
Next |
|||
Next |
|||
ProcedureReturn #True ;multiplication performed, product in prd() |
|||
Else |
|||
ProcedureReturn #False ;multiplication not performed, dimensions invalid |
|||
EndIf |
|||
EndProcedure</lang> |
|||
Additional code to demonstrate use. |
|||
<lang PureBasic>DataSection |
|||
Data.i 2,3 ;matrix a (#rows, #cols) |
|||
Data.i 1,2,3, 4,5,6 ;elements by row |
|||
Data.i 3,1 ;matrix b (#rows, #cols) |
|||
Data.i 1, 5, 9 ;elements by row |
|||
EndDataSection |
|||
Procedure displayMatrix(Array a(2), text.s) |
|||
Protected i, j |
|||
Protected columns = ArraySize(a(), 2), Rows = ArraySize(a(), 1) |
|||
PrintN(text + ": (" + Str(Rows + 1) + ", " + Str(columns + 1) + ")") |
|||
For i = 0 To Rows |
|||
For j = 0 To columns |
|||
Print(LSet(Str(a(i, j)), 4, " ")) |
|||
Next |
|||
PrintN("") |
|||
Next |
|||
PrintN("") |
|||
EndProcedure |
|||
Procedure loadMatrix(Array a(2)) |
|||
Protected Rows, columns, i, j |
|||
Read.i Rows |
|||
Read.i columns |
|||
Dim a(Rows - 1, columns - 1) |
|||
For i = 0 To Rows - 1 |
|||
For j = 0 To columns - 1 |
|||
Read.i a(i, j) |
|||
Next |
|||
Next |
|||
EndProcedure |
|||
Dim a(0,0) |
|||
Dim b(0,0) |
|||
Dim c(0,0) |
|||
If OpenConsole() |
|||
loadMatrix(a()) |
|||
displayMatrix(a(), "matrix a") |
|||
loadMatrix(b()) |
|||
displayMatrix(b(), "matrix b") |
|||
If multiplyMatrix(a(), b(), c()) |
|||
displayMatrix(c(), "product of a * b") |
|||
Else |
|||
PrintN("product of a * b is undefined") |
|||
EndIf |
|||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") |
|||
Input() |
|||
CloseConsole() |
|||
EndIf</lang> |
|||
Sample output: |
|||
<pre>matrix a: (2, 3) |
|||
1 2 3 |
|||
4 5 6 |
|||
matrix b: (3, 1) |
|||
1 |
|||
5 |
|||
9 |
|||
product of a * b: (2, 1) |
|||
38 |
|||
83</pre> |
|||
=={{header|Python}}== |
=={{header|Python}}== |