Matrix multiplication: Difference between revisions

Content added Content deleted
m (Applesoft BASIC header)
m (syntax highlighting fixup automation)
Line 10: Line 10:
{{trans|Nim}}
{{trans|Nim}}


<lang 11l>F matrix_mul(m1, m2)
<syntaxhighlight lang="11l">F matrix_mul(m1, m2)
assert(m1[0].len == m2.len)
assert(m1[0].len == m2.len)
V r = [[0.0] * m2[0].len] * m1.len
V r = [[0.0] * m2[0].len] * m1.len
Line 43: Line 43:
print(to_str(b))
print(to_str(b))
print(to_str(matrix_mul(a, b)))
print(to_str(matrix_mul(a, b)))
print(to_str(matrix_mul(b, a)))</lang>
print(to_str(matrix_mul(b, a)))</syntaxhighlight>


{{out}}
{{out}}
Line 66: Line 66:


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Matrix multiplication 06/08/2015
<syntaxhighlight lang="360asm">* Matrix multiplication 06/08/2015
MATRIXRC CSECT Matrix multiplication
MATRIXRC CSECT Matrix multiplication
USING MATRIXRC,R13
USING MATRIXRC,R13
Line 171: Line 171:
W DS CL16
W DS CL16
YREGS
YREGS
END MATRIXRC</lang>
END MATRIXRC</syntaxhighlight>
{{out}}
{{out}}
<pre> 9 12 15
<pre> 9 12 15
Line 180: Line 180:
=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang="action!">INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit


DEFINE PTR="CARD"
DEFINE PTR="CARD"
Line 259: Line 259:
PutE() PrintE("equals") PutE()
PutE() PrintE("equals") PutE()
PrintMatrix(res)
PrintMatrix(res)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Matrix_multiplication.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Matrix_multiplication.png Screenshot from Atari 8-bit computer]
Line 281: Line 281:
Ada has matrix multiplication predefined for any floating-point or complex type.
Ada has matrix multiplication predefined for any floating-point or complex type.
The implementation is provided by the standard library packages Ada.Numerics.Generic_Real_Arrays and Ada.Numerics.Generic_Complex_Arrays correspondingly. The following example illustrates use of real matrix multiplication for the type Float:
The implementation is provided by the standard library packages Ada.Numerics.Generic_Real_Arrays and Ada.Numerics.Generic_Complex_Arrays correspondingly. The following example illustrates use of real matrix multiplication for the type Float:
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;


Line 311: Line 311:
begin
begin
Put (A * B);
Put (A * B);
end Matrix_Product;</lang>
end Matrix_Product;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 320: Line 320:
</pre>
</pre>
The following code illustrates how matrix multiplication could be implemented from scratch:
The following code illustrates how matrix multiplication could be implemented from scratch:
<lang ada>package Matrix_Ops is
<syntaxhighlight lang="ada">package Matrix_Ops is
type Matrix is array (Natural range <>, Natural range <>) of Float;
type Matrix is array (Natural range <>, Natural range <>) of Float;
function "*" (Left, Right : Matrix) return Matrix;
function "*" (Left, Right : Matrix) return Matrix;
Line 345: Line 345:
return Temp;
return Temp;
end "*";
end "*";
end Matrix_Ops;</lang>
end Matrix_Ops;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 353: Line 353:
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
An example of user defined Vector and Matrix Multiplication Operators:
An example of user defined Vector and Matrix Multiplication Operators:
<lang algol68>MODE FIELD = LONG REAL; # field type is LONG REAL #
<syntaxhighlight lang="algol68">MODE FIELD = LONG REAL; # field type is LONG REAL #
INT default upb:=3;
INT default upb:=3;
MODE VECTOR = [default upb]FIELD;
MODE VECTOR = [default upb]FIELD;
Line 412: Line 412:
exception index error:
exception index error:
putf(stand error, $x"Exception: index error."l$)
putf(stand error, $x"Exception: index error."l$)
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 523: Line 523:


=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
#include <hopper.h>
main:
main:
Line 531: Line 531:
{first matrix,second matrix},mat mul, println
{first matrix,second matrix},mat mul, println
exit(0)
exit(0)
</syntaxhighlight>
</lang>
Alternatively, the follow code in macro-natural-Hopper:
Alternatively, the follow code in macro-natural-Hopper:
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <natural.h>
#include <natural.h>
#include <hopper.h>
#include <hopper.h>
Line 541: Line 541:
now take 'first matrix', and take 'second matrix', and multiply it; then, print with a new line.
now take 'first matrix', and take 'second matrix', and multiply it; then, print with a new line.
exit(0)
exit(0)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 563: Line 563:
Matrix multiply in APL is just <tt>+.×</tt>. For example:
Matrix multiply in APL is just <tt>+.×</tt>. For example:


<lang apl> x ← +.×
<syntaxhighlight lang="apl"> x ← +.×
A ← ↑A*¨⊂A←⍳4 ⍝ Same A as in other examples (1 1 1 1⍪ 2 4 8 16⍪ 3 9 27 81,[0.5] 4 16 64 256)
A ← ↑A*¨⊂A←⍳4 ⍝ Same A as in other examples (1 1 1 1⍪ 2 4 8 16⍪ 3 9 27 81,[0.5] 4 16 64 256)
Line 572: Line 572:
0.00 1.00 0.00 0.00
0.00 1.00 0.00 0.00
0.00 0.00 1.00 0.00
0.00 0.00 1.00 0.00
0.00 0.00 0.00 1.00</lang>
0.00 0.00 0.00 1.00</syntaxhighlight>


By contrast, A×B is for element-by-element multiplication of arrays of the same shape, and if they are simple elements, this is ordinary multiplication.
By contrast, A×B is for element-by-element multiplication of arrays of the same shape, and if they are simple elements, this is ordinary multiplication.
Line 588: Line 588:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
<lang AppleScript>--------------------- MATRIX MULTIPLY --------------------
<syntaxhighlight lang="applescript">--------------------- MATRIX MULTIPLY --------------------


-- matrixMultiply :: Num a => [[a]] -> [[a]] -> [[a]]
-- matrixMultiply :: Num a => [[a]] -> [[a]] -> [[a]]
Line 746: Line 746:
return lst
return lst
end tell
end tell
end zipWith</lang>
end zipWith</syntaxhighlight>
{{Out}}
{{Out}}
<lang AppleScript>{{51, -8, 26, -18}, {-8, -38, -6, 34}, {33, 42, 38, -14}, {17, 74, 72, 44}}</lang>
<syntaxhighlight lang="applescript">{{51, -8, 26, -18}, {-8, -38, -6, 34}, {33, 42, 38, -14}, {17, 74, 72, 44}}</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>printMatrix: function [m][
<syntaxhighlight lang="rebol">printMatrix: function [m][
loop m 'row -> print map row 'val [pad to :string .format:".2f" val 6]
loop m 'row -> print map row 'val [pad to :string .format:".2f" val 6]
print "--------------------------------"
print "--------------------------------"
Line 784: Line 784:
printMatrix B
printMatrix B
printMatrix multiply A B
printMatrix multiply A B
printMatrix multiply B A</lang>
printMatrix multiply B A</syntaxhighlight>


{{out}}
{{out}}
Line 811: Line 811:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
ahk [http://www.autohotkey.com/forum/topic44657-150.html discussion]
ahk [http://www.autohotkey.com/forum/topic44657-150.html discussion]
<lang autohotkey>Matrix("b"," ; rows separated by ","
<syntaxhighlight lang="autohotkey">Matrix("b"," ; rows separated by ","
, 1 2 ; entries separated by space or tab
, 1 2 ; entries separated by space or tab
, 2 3
, 2 3
Line 862: Line 862:
}
}
}
}
}</lang>
}</syntaxhighlight>
===Using Objects===
===Using Objects===
<lang AutoHotkey>Multiply_Matrix(A,B){
<syntaxhighlight lang="autohotkey">Multiply_Matrix(A,B){
if (A[1].Count() <> B.Count())
if (A[1].Count() <> B.Count())
return ["Dimension Error"]
return ["Dimension Error"]
Line 878: Line 878:
}
}
return R
return R
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>A := [[1,2]
Examples:<syntaxhighlight lang="autohotkey">A := [[1,2]
, [3,4]
, [3,4]
, [5,6]
, [5,6]
Line 897: Line 897:
Res .= (A_Index=1?"":"`t") col (Mod(A_Index,M[1].MaxIndex())?"":"`n")
Res .= (A_Index=1?"":"`t") col (Mod(A_Index,M[1].MaxIndex())?"":"`n")
return Trim(Res,"`n")
return Trim(Res,"`n")
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>9 12 15
<pre>9 12 15
Line 905: Line 905:


=={{header|AWK}}==
=={{header|AWK}}==
<lang AWK># Usage: GAWK -f MATRIX_MULTIPLICATION.AWK filename
<syntaxhighlight lang="awk"># Usage: GAWK -f MATRIX_MULTIPLICATION.AWK filename
# Separate matrices a and b by a blank line
# Separate matrices a and b by a blank line
BEGIN {
BEGIN {
Line 958: Line 958:
function max(m, n) {
function max(m, n) {
return m > n ? m : n
return m > n ? m : n
}</lang>
}</syntaxhighlight>
<p><b>Input:</b></p>
<p><b>Input:</b></p>
<pre>
<pre>
Line 977: Line 977:
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
{{trans|Java}}
{{trans|Java}}
<lang qbasic>Assume the matrices to be multiplied are a and b
<syntaxhighlight lang="qbasic">Assume the matrices to be multiplied are a and b
IF (LEN(a,2) = LEN(b)) 'if valid dims
IF (LEN(a,2) = LEN(b)) 'if valid dims
n = LEN(a,2)
n = LEN(a,2)
Line 1,000: Line 1,000:
ELSE
ELSE
PRINT "invalid dimensions"
PRINT "invalid dimensions"
END IF</lang>
END IF</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
A nine-liner that fits on one screen. The code and variable names are similar to [[#BASIC|BASIC]] with DATA from [[Full_BASIC|Full BASIC]].
A nine-liner that fits on one screen. The code and variable names are similar to [[#BASIC|BASIC]] with DATA from [[Full_BASIC|Full BASIC]].
<lang gwbasic> 1 FOR K = 0 TO 1:M = O:N = P: READ O,P: IF K THEN DIM B(O,P): IF N < > O THEN PRINT "INVALID DIMENSIONS": STOP
<syntaxhighlight lang="gwbasic"> 1 FOR K = 0 TO 1:M = O:N = P: READ O,P: IF K THEN DIM B(O,P): IF N < > O THEN PRINT "INVALID DIMENSIONS": STOP
2 IF NOT K THEN DIM A(O,P)
2 IF NOT K THEN DIM A(O,P)
3 FOR I = 1 TO O: FOR J = 1 TO P: IF K THEN READ B(I,J)
3 FOR I = 1 TO O: FOR J = 1 TO P: IF K THEN READ B(I,J)
Line 1,012: Line 1,012:
10010 DATA1,2,3,4,5,6,7,8
10010 DATA1,2,3,4,5,6,7,8
20000 DATA2,3
20000 DATA2,3
20010 DATA1,2,3,4,5,6</lang>
20010 DATA1,2,3,4,5,6</syntaxhighlight>


===Full BASIC===
===Full BASIC===
{{works with|Full BASIC}}
{{works with|Full BASIC}}
{{trans|BBC_BASIC}}
{{trans|BBC_BASIC}}
<lang basic>DIM matrix1(4,2),matrix2(2,3)
<syntaxhighlight lang="basic">DIM matrix1(4,2),matrix2(2,3)


MAT READ matrix1
MAT READ matrix1
Line 1,030: Line 1,030:


MAT product=matrix1*matrix2
MAT product=matrix1*matrix2
MAT PRINT product</lang>
MAT PRINT product</syntaxhighlight>
{{out}}
{{out}}
<pre> 9 12 15
<pre> 9 12 15
Line 1,041: Line 1,041:
(assumes default lower bound of 0):
(assumes default lower bound of 0):


<lang bbcbasic> DIM matrix1(3,1), matrix2(1,2), product(3,2)
<syntaxhighlight lang="bbcbasic"> DIM matrix1(3,1), matrix2(1,2), product(3,2)
matrix1() = 1, 2, \
matrix1() = 1, 2, \
Line 1,059: Line 1,059:
PRINT
PRINT
NEXT
NEXT
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre> 9 12 15
<pre> 9 12 15
Line 1,069: Line 1,069:
<code>Mul</code> is a matrix multiplication idiom from [https://mlochbaum.github.io/bqncrate/ BQNcrate.]
<code>Mul</code> is a matrix multiplication idiom from [https://mlochbaum.github.io/bqncrate/ BQNcrate.]


<lang bqn>Mul ← +˝∘×⎉1‿∞
<syntaxhighlight lang="bqn">Mul ← +˝∘×⎉1‿∞


(>⟨
(>⟨
Line 1,079: Line 1,079:
⟨5, 6, 7, 8⟩
⟨5, 6, 7, 8⟩
⟨9, 10, 11, 12⟩
⟨9, 10, 11, 12⟩
⟩</lang><lang bqn>┌─
⟩</syntaxhighlight><syntaxhighlight lang="bqn">┌─
╵ 20 23 26 29
╵ 20 23 26 29
56 68 80 92
56 68 80 92
92 113 134 155
92 113 134 155
┘</lang>
┘</syntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=TXVsIOKGkCAry53iiJjDl+KOiTHigL/iiJ4KCig+4p+oCiAg4p+oMSwgMiwgM+KfqQogIOKfqDQsIDUsIDbin6kKICDin6g3LCA4LCA54p+pCuKfqSkgTXVsID7in6gKICDin6gxLCAgMiwgIDMsIDTin6kKICDin6g1LCAgNiwgIDcsIDjin6kKICDin6g5LCAxMCwgMTEsIDEy4p+pCuKfqQo= Try It!]
[https://mlochbaum.github.io/BQN/try.html#code=TXVsIOKGkCAry53iiJjDl+KOiTHigL/iiJ4KCig+4p+oCiAg4p+oMSwgMiwgM+KfqQogIOKfqDQsIDUsIDbin6kKICDin6g3LCA4LCA54p+pCuKfqSkgTXVsID7in6gKICDin6gxLCAgMiwgIDMsIDTin6kKICDin6g1LCAgNiwgIDcsIDjin6kKICDin6g5LCAxMCwgMTEsIDEy4p+pCuKfqQo= Try It!]


=={{header|Burlesque}}==
=={{header|Burlesque}}==


<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) {{1 2}{3 4}{5 6}{7 8}}{{1 2 3}{4 5 6}}mmsp
blsq ) {{1 2}{3 4}{5 6}{7 8}}{{1 2 3}{4 5 6}}mmsp
9 12 15
9 12 15
Line 1,094: Line 1,094:
29 40 51
29 40 51
39 54 69
39 54 69
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


#define MAT_ELEM(rows,cols,r,c) (r*cols+c)
#define MAT_ELEM(rows,cols,r,c) (r*cols+c)
Line 1,160: Line 1,160:
}
}


</syntaxhighlight>
</lang>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Line 1,166: Line 1,166:
This code should work with any version of the .NET Framework and C# language
This code should work with any version of the .NET Framework and C# language


<lang csharp>public class Matrix
<syntaxhighlight lang="csharp">public class Matrix
{
{
int n;
int n;
Line 1,209: Line 1,209:
return result;
return result;
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 1,216: Line 1,216:


{{libheader|Blitz++}}
{{libheader|Blitz++}}
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <blitz/tinymat.h>
#include <blitz/tinymat.h>


Line 1,236: Line 1,236:


std::cout << C << std::endl;
std::cout << C << std::endl;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
(3,3):
(3,3):
Line 1,245: Line 1,245:
===Generic solution===
===Generic solution===
main.cpp
main.cpp
<lang cpp>
<syntaxhighlight lang="cpp">
#include <iostream>
#include <iostream>
#include "matrix.h"
#include "matrix.h"
Line 1,282: Line 1,282:


} /* main() */
} /* main() */
</syntaxhighlight>
</lang>


matrix.h
matrix.h
<lang cpp>
<syntaxhighlight lang="cpp">
#ifndef _MATRIX_H
#ifndef _MATRIX_H
#define _MATRIX_H
#define _MATRIX_H
Line 1,463: Line 1,463:


#endif /* _MATRIX_H */
#endif /* _MATRIX_H */
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,472: Line 1,472:


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>alias Matrix => Integer[][];
<syntaxhighlight lang="ceylon">alias Matrix => Integer[][];


void printMatrix(Matrix m) {
void printMatrix(Matrix m) {
Line 1,536: Line 1,536:
print("something went wrong!");
print("something went wrong!");
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[1, 2, 3]
<pre>[1, 2, 3]
Line 1,553: Line 1,553:


Overload the '*' operator for arrays
Overload the '*' operator for arrays
<lang chapel>proc *(a:[], b:[]) {
<syntaxhighlight lang="chapel">proc *(a:[], b:[]) {


if (a.eltType != b.eltType) then
if (a.eltType != b.eltType) then
Line 1,573: Line 1,573:


return c;
return c;
}</lang>
}</syntaxhighlight>


example usage (I could not figure out the syntax for multi-dimensional array literals)
example usage (I could not figure out the syntax for multi-dimensional array literals)
<lang chapel>var m1:[{1..2, 1..2}] int;
<syntaxhighlight lang="chapel">var m1:[{1..2, 1..2}] int;
m1(1,1) = 1; m1(1,2) = 2;
m1(1,1) = 1; m1(1,2) = 2;
m1(2,1) = 3; m1(2,2) = 4;
m1(2,1) = 3; m1(2,2) = 4;
Line 1,600: Line 1,600:
writeln(m5);
writeln(m5);


writeln(m4 * m5);</lang>
writeln(m4 * m5);</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==


<lang lisp>
<syntaxhighlight lang="lisp">
(defn transpose
(defn transpose
[s]
[s]
Line 1,621: Line 1,621:


(def ma [[1 1 1 1] [2 4 8 16] [3 9 27 81] [4 16 64 256]])
(def ma [[1 1 1 1] [2 4 8 16] [3 9 27 81] [4 16 64 256]])
(def mb [[4 -3 4/3 -1/4] [-13/3 19/4 -7/3 11/24] [3/2 -2 7/6 -1/4] [-1/6 1/4 -1/6 1/24]])</lang>
(def mb [[4 -3 4/3 -1/4] [-13/3 19/4 -7/3 11/24] [3/2 -2 7/6 -1/4] [-1/6 1/4 -1/6 1/24]])</syntaxhighlight>


{{out}}
{{out}}
Line 1,630: Line 1,630:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun matrix-multiply (a b)
<syntaxhighlight lang="lisp">(defun matrix-multiply (a b)
(flet ((col (mat i) (mapcar #'(lambda (row) (elt row i)) mat))
(flet ((col (mat i) (mapcar #'(lambda (row) (elt row i)) mat))
(row (mat i) (elt mat i)))
(row (mat i) (elt mat i)))
Line 1,638: Line 1,638:


;; example use:
;; example use:
(matrix-multiply '((1 2) (3 4)) '((-3 -8 3) (-2 1 4)))</lang>
(matrix-multiply '((1 2) (3 4)) '((-3 -8 3) (-2 1 4)))</syntaxhighlight>


<lang lisp>(defun matrix-multiply (matrix1 matrix2)
<syntaxhighlight lang="lisp">(defun matrix-multiply (matrix1 matrix2)
(mapcar
(mapcar
(lambda (row)
(lambda (row)
(apply #'mapcar
(apply #'mapcar
(lambda (&rest column)
(lambda (&rest column)
(apply #'+ (mapcar #'* row column))) matrix2)) matrix1))</lang>
(apply #'+ (mapcar #'* row column))) matrix2)) matrix1))</syntaxhighlight>


The following version uses 2D arrays as inputs.
The following version uses 2D arrays as inputs.


<lang lisp>(defun mmul (A B)
<syntaxhighlight lang="lisp">(defun mmul (A B)
(let* ((m (car (array-dimensions A)))
(let* ((m (car (array-dimensions A)))
(n (cadr (array-dimensions A)))
(n (cadr (array-dimensions A)))
Line 1,660: Line 1,660:
sum (* (aref A i j)
sum (* (aref A i j)
(aref B j k))))))
(aref B j k))))))
C))</lang>
C))</syntaxhighlight>


Example use:
Example use:


<lang lisp>(mmul #2a((1 2) (3 4)) #2a((-3 -8 3) (-2 1 4)))
<syntaxhighlight lang="lisp">(mmul #2a((1 2) (3 4)) #2a((-3 -8 3) (-2 1 4)))
#2A((-7 -6 11) (-17 -20 25))
#2A((-7 -6 11) (-17 -20 25))
</syntaxhighlight>
</lang>


Another version:
Another version:


<lang lisp>(defun mmult (a b)
<syntaxhighlight lang="lisp">(defun mmult (a b)
(loop
(loop
with m = (array-dimension a 0)
with m = (array-dimension a 0)
Line 1,682: Line 1,682:
sum (* (aref a i j)
sum (* (aref a i j)
(aref b j k)))))
(aref b j k)))))
finally (return c)))</lang>
finally (return c)))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
===Basic Version===
===Basic Version===
<lang d>import std.stdio, std.string, std.conv, std.numeric,
<syntaxhighlight lang="d">import std.stdio, std.string, std.conv, std.numeric,
std.array, std.algorithm;
std.array, std.algorithm;


Line 1,719: Line 1,719:
writefln("B = \n" ~ form ~ "\n", b);
writefln("B = \n" ~ form ~ "\n", b);
writefln("A * B = \n" ~ form, matrixMul(a, b));
writefln("A * B = \n" ~ form, matrixMul(a, b));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>A =
<pre>A =
Line 1,736: Line 1,736:


===Short Version===
===Short Version===
<lang d>import std.stdio, std.range, std.array, std.numeric, std.algorithm;
<syntaxhighlight lang="d">import std.stdio, std.range, std.array, std.numeric, std.algorithm;


T[][] matMul(T)(in T[][] A, in T[][] B) pure nothrow /*@safe*/ {
T[][] matMul(T)(in T[][] A, in T[][] B) pure nothrow /*@safe*/ {
Line 1,751: Line 1,751:
writefln("B = \n" ~ form ~ "\n", b);
writefln("B = \n" ~ form ~ "\n", b);
writefln("A * B = \n" ~ form, matMul(a, b));
writefln("A * B = \n" ~ form, matMul(a, b));
}</lang>
}</syntaxhighlight>
The output is the same.
The output is the same.


===Pure Short Version===
===Pure Short Version===
<lang d>import std.stdio, std.range, std.numeric, std.algorithm;
<syntaxhighlight lang="d">import std.stdio, std.range, std.numeric, std.algorithm;


T[][] matMul(T)(immutable T[][] A, immutable T[][] B) pure nothrow {
T[][] matMul(T)(immutable T[][] A, immutable T[][] B) pure nothrow {
Line 1,771: Line 1,771:
writefln("B = \n" ~ form ~ "\n", b);
writefln("B = \n" ~ form ~ "\n", b);
writefln("A * B = \n" ~ form, matMul(a, b));
writefln("A * B = \n" ~ form, matMul(a, b));
}</lang>
}</syntaxhighlight>
The output is the same.
The output is the same.


Line 1,777: Line 1,777:
All array sizes are verified at compile-time (and no matrix is copied).
All array sizes are verified at compile-time (and no matrix is copied).
Same output.
Same output.
<lang d>import std.stdio, std.string, std.numeric, std.algorithm, std.traits;
<syntaxhighlight lang="d">import std.stdio, std.string, std.numeric, std.algorithm, std.traits;


alias TMMul_helper(M1, M2) = Unqual!(ForeachType!(ForeachType!M1))
alias TMMul_helper(M1, M2) = Unqual!(ForeachType!(ForeachType!M1))
Line 1,809: Line 1,809:
matrixMul(a, b, result);
matrixMul(a, b, result);
writefln("A * B = \n" ~ form, result);
writefln("A * B = \n" ~ form, result);
}</lang>
}</syntaxhighlight>
=={{header|Delphi}}==
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.SysUtils}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Matrix_multiplication;
program Matrix_multiplication;


Line 1,905: Line 1,905:
readln;
readln;


end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>a:
<pre>a:
Line 1,922: Line 1,922:
[117,00, 117,00, 117,00]]</pre>
[117,00, 117,00, 117,00]]</pre>
=={{header|EGL}}==
=={{header|EGL}}==
<syntaxhighlight lang="egl">
<lang EGL>
program Matrix_multiplication type BasicProgram {}
program Matrix_multiplication type BasicProgram {}
Line 1,957: Line 1,957:
end
end
end
end
</syntaxhighlight>
</lang>


=={{header|Ela}}==
=={{header|Ela}}==


<lang ela>open list
<syntaxhighlight lang="ela">open list


mmult a b = [ [ sum $ zipWith (*) ar bc \\ bc <- (transpose b) ] \\ ar <- a ]
mmult a b = [ [ sum $ zipWith (*) ar bc \\ bc <- (transpose b) ] \\ ar <- a ]
Line 1,967: Line 1,967:
[[1, 2],
[[1, 2],
[3, 4]] `mmult` [[-3, -8, 3],
[3, 4]] `mmult` [[-3, -8, 3],
[-2, 1, 4]]</lang>
[-2, 1, 4]]</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>
<syntaxhighlight lang="elixir">
def mult(m1, m2) do
def mult(m1, m2) do
Enum.map m1, fn (x) -> Enum.map t(m2), fn (y) -> Enum.zip(x, y)
Enum.map m1, fn (x) -> Enum.map t(m2), fn (y) -> Enum.zip(x, y)
Line 1,984: Line 1,984:




</syntaxhighlight>
</lang>


=={{header|ELLA}}==
=={{header|ELLA}}==
Line 1,990: Line 1,990:


Code for matrix multiplication hardware design verification:
Code for matrix multiplication hardware design verification:
<lang ella>MAC ZIP = ([INT n]TYPE t: vector1 vector2) -> [n][2]t:
<syntaxhighlight lang="ella">MAC ZIP = ([INT n]TYPE t: vector1 vector2) -> [n][2]t:
[INT k = 1..n](vector1[k], vector2[k]).
[INT k = 1..n](vector1[k], vector2[k]).
Line 2,034: Line 2,034:
).
).


COM test: just displaysignal MOC</lang>
COM test: just displaysignal MOC</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>
<syntaxhighlight lang="erlang">


%% Multiplies two matrices. Usage example:
%% Multiplies two matrices. Usage example:
Line 2,096: Line 2,096:
multiply_row_by_col(Row, []) ->
multiply_row_by_col(Row, []) ->
[].
[].
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,104: Line 2,104:


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM MAT_PROD
PROGRAM MAT_PROD


Line 2,142: Line 2,142:


END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}<pre>
{{out}}<pre>
9 12 15
9 12 15
Line 2,151: Line 2,151:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function matrix_mul(sequence a, sequence b)
<syntaxhighlight lang="euphoria">function matrix_mul(sequence a, sequence b)
sequence c
sequence c
if length(a[1]) != length(b) then
if length(a[1]) != length(b) then
Line 2,166: Line 2,166:
return c
return c
end if
end if
end function</lang>
end function</syntaxhighlight>


=={{header|Excel}}==
=={{header|Excel}}==
Line 2,254: Line 2,254:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
let MatrixMultiply (matrix1 : _[,] , matrix2 : _[,]) =
let MatrixMultiply (matrix1 : _[,] , matrix2 : _[,]) =
let result_row = (matrix1.GetLength 0)
let result_row = (matrix1.GetLength 0)
Line 2,267: Line 2,267:
ret
ret


</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
Line 2,280: Line 2,280:
Using a list of lists representation. The multiplication is done using three nested loops.
Using a list of lists representation. The multiplication is done using three nested loops.


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 2,312: Line 2,312:
}
}
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,320: Line 2,320:


=={{header|Fermat}}==
=={{header|Fermat}}==
<lang fermat>
<syntaxhighlight lang="fermat">
Array a[3,2]
Array a[3,2]
Array b[2,3]
Array b[2,3]
Line 2,326: Line 2,326:
[b]:=[(1,1,2,3,5,8)]
[b]:=[(1,1,2,3,5,8)]
[a]*[b]
[a]*[b]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,337: Line 2,337:
{{libheader|Forth Scientific Library}}
{{libheader|Forth Scientific Library}}
{{works with|gforth|0.7.9_20170308}}
{{works with|gforth|0.7.9_20170308}}
<lang forth>S" fsl-util.fs" REQUIRED
<syntaxhighlight lang="forth">S" fsl-util.fs" REQUIRED
S" fsl/dynmem.seq" REQUIRED
S" fsl/dynmem.seq" REQUIRED
: F+! ( addr -- ) ( F: r -- ) DUP F@ F+ F! ;
: F+! ( addr -- ) ( F: r -- ) DUP F@ F+ F! ;
Line 2,350: Line 2,350:
A{{ 3 3 B{{ 3 3 & C{{ mat*
A{{ 3 3 B{{ 3 3 & C{{ mat*
3 3 C{{ }}fprint</lang>
3 3 C{{ }}fprint</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
In ISO Fortran 90 or later, use the MATMUL intrinsic function to perform Matrix Multiply; use RESHAPE and SIZE intrinsic functions to form the matrices themselves:
In ISO Fortran 90 or later, use the MATMUL intrinsic function to perform Matrix Multiply; use RESHAPE and SIZE intrinsic functions to form the matrices themselves:
<lang fortran>real, dimension(n,m) :: a = reshape( [ (i, i=1, n*m) ], [ n, m ] )
<syntaxhighlight lang="fortran">real, dimension(n,m) :: a = reshape( [ (i, i=1, n*m) ], [ n, m ] )
real, dimension(m,k) :: b = reshape( [ (i, i=1, m*k) ], [ m, k ] )
real, dimension(m,k) :: b = reshape( [ (i, i=1, m*k) ], [ m, k ] )
real, dimension(size(a,1), size(b,2)) :: c ! C is an array whose first dimension (row) size
real, dimension(size(a,1), size(b,2)) :: c ! C is an array whose first dimension (row) size
Line 2,378: Line 2,378:
do i = 1, n
do i = 1, n
print *, c(i,:)
print *, c(i,:)
end do</lang>
end do</syntaxhighlight>
For Intel 14.x or later (with compiler switch -assume realloc_lhs)
For Intel 14.x or later (with compiler switch -assume realloc_lhs)
<lang fortran>
<syntaxhighlight lang="fortran">
program mm
program mm
real , allocatable :: a(:,:),b(:,:)
real , allocatable :: a(:,:),b(:,:)
Line 2,388: Line 2,388:
print'(<n>f15.7)',transpose(matmul(a,b))
print'(<n>f15.7)',transpose(matmul(a,b))
end program
end program
</syntaxhighlight>
</lang>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>type Matrix
<syntaxhighlight lang="freebasic">type Matrix
dim as double m( any , any )
dim as double m( any , any )
declare constructor ( )
declare constructor ( )
Line 2,434: Line 2,434:
print c.m(2, 0), c.m(2, 1), c.m(2, 2), c.m(2, 3)
print c.m(2, 0), c.m(2, 1), c.m(2, 2), c.m(2, 3)
print c.m(3, 0), c.m(3, 1), c.m(3, 2), c.m(3, 3)
print c.m(3, 0), c.m(3, 1), c.m(3, 2), c.m(3, 3)
</syntaxhighlight>
</lang>




=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>matprod[a is array, b is array] :=
<syntaxhighlight lang="frink">matprod[a is array, b is array] :=
{
{
c = makeArray[[length[a], length[b@0]], 0]
c = makeArray[[length[a], length[b@0]], 0]
Line 2,452: Line 2,452:


return c
return c
}</lang>
}</syntaxhighlight>


=={{header|Futhark}}==
=={{header|Futhark}}==
Line 2,459: Line 2,459:
Note that the transposition need not be manifested, but is merely a change of indexing.
Note that the transposition need not be manifested, but is merely a change of indexing.


<syntaxhighlight lang="futhark">
<lang Futhark>
fun main(x: [n][m]int, y: [m][p]int): [n][p]int =
fun main(x: [n][m]int, y: [m][p]int): [n][p]int =
map (fn xr => map (fn yc => reduce (+) 0 (zipWith (*) xr yc))
map (fn xr => map (fn yc => reduce (+) 0 (zipWith (*) xr yc))
(transpose y))
(transpose y))
x
x
</syntaxhighlight>
</lang>


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># Built-in
<syntaxhighlight lang="gap"># Built-in
A := [[1, 2], [3, 4], [5, 6], [7, 8]];
A := [[1, 2], [3, 4], [5, 6], [7, 8]];
B := [[1, 2, 3], [4, 5, 6]];
B := [[1, 2, 3], [4, 5, 6]];
Line 2,485: Line 2,485:
# [ 19, 26, 33 ],
# [ 19, 26, 33 ],
# [ 29, 40, 51 ],
# [ 29, 40, 51 ],
# [ 39, 54, 69 ] ]</lang>
# [ 39, 54, 69 ] ]</syntaxhighlight>




=={{header|Generic}}==
=={{header|Generic}}==
<lang cpp>
<syntaxhighlight lang="cpp">
generic coordinaat
generic coordinaat
{
{
Line 3,159: Line 3,159:


}
}
</syntaxhighlight>
</lang>


=={{header|Go}}==
=={{header|Go}}==
===Library gonum/mat===
===Library gonum/mat===
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 3,185: Line 3,185:
m.Mul(a, b)
m.Mul(a, b)
fmt.Println(mat.Formatted(&m))
fmt.Println(mat.Formatted(&m))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,193: Line 3,193:


===Library go.matrix===
===Library go.matrix===
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 3,220: Line 3,220:
}
}
fmt.Printf("Product of A and B:\n%v\n", p)
fmt.Printf("Product of A and B:\n%v\n", p)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,237: Line 3,237:


===2D representation===
===2D representation===
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 3,296: Line 3,296:
fmt.Printf("Matrix B:\n%s\n\n", B)
fmt.Printf("Matrix B:\n%s\n\n", B)
fmt.Printf("Product of A and B:\n%s\n\n", P)
fmt.Printf("Product of A and B:\n%s\n\n", P)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,314: Line 3,314:
</pre>
</pre>
===Flat representation===
===Flat representation===
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 3,369: Line 3,369:
}
}
p.print("Product of A and B:")
p.print("Product of A and B:")
}</lang>
}</syntaxhighlight>
Output is similar to 2D version.
Output is similar to 2D version.


Line 3,375: Line 3,375:
=== Without Indexed Loops ===
=== Without Indexed Loops ===
Uses transposition to avoid indirect element access via ranges of indexes. "assertConformable()" asserts that a & b are both rectangular lists of lists, and that row-length (number of columns) of a is equal to the column-length (number of rows) of b.
Uses transposition to avoid indirect element access via ranges of indexes. "assertConformable()" asserts that a & b are both rectangular lists of lists, and that row-length (number of columns) of a is equal to the column-length (number of rows) of b.
<lang groovy>def assertConformable = { a, b ->
<syntaxhighlight lang="groovy">def assertConformable = { a, b ->
assert a instanceof List
assert a instanceof List
assert b instanceof List
assert b instanceof List
Line 3,391: Line 3,391:
}
}
}
}
}</lang>
}</syntaxhighlight>


=== Without Transposition ===
=== Without Transposition ===
Uses ranges of indexes, the way that matrix multiplication is typically defined. Not as elegant, but it avoids expensive transpositions. Reuses "assertConformable()" from above.
Uses ranges of indexes, the way that matrix multiplication is typically defined. Not as elegant, but it avoids expensive transpositions. Reuses "assertConformable()" from above.
<lang groovy>def matmulWOT = { a, b ->
<syntaxhighlight lang="groovy">def matmulWOT = { a, b ->
assertConformable(a, b)
assertConformable(a, b)
Line 3,403: Line 3,403:
}
}
}
}
}</lang>
}</syntaxhighlight>


Test:
Test:
<lang groovy>def m4by2 = [ [ 1, 2 ],
<syntaxhighlight lang="groovy">def m4by2 = [ [ 1, 2 ],
[ 3, 4 ],
[ 3, 4 ],
[ 5, 6 ],
[ 5, 6 ],
Line 3,416: Line 3,416:
matmulWOIL(m4by2, m2by3).each { println it }
matmulWOIL(m4by2, m2by3).each { println it }
println()
println()
matmulWOT(m4by2, m2by3).each { println it }</lang>
matmulWOT(m4by2, m2by3).each { println it }</syntaxhighlight>


{{out}}
{{out}}
Line 3,433: Line 3,433:
A somewhat inefficient version with lists (''transpose'' is expensive):
A somewhat inefficient version with lists (''transpose'' is expensive):


<lang Haskell>import Data.List
<syntaxhighlight lang="haskell">import Data.List


mmult :: Num a => [[a]] -> [[a]] -> [[a]]
mmult :: Num a => [[a]] -> [[a]] -> [[a]]
Line 3,441: Line 3,441:
test = [[1, 2],
test = [[1, 2],
[3, 4]] `mmult` [[-3, -8, 3],
[3, 4]] `mmult` [[-3, -8, 3],
[-2, 1, 4]]</lang>
[-2, 1, 4]]</syntaxhighlight>
===With Array===
===With Array===
A more efficient version, based on arrays:
A more efficient version, based on arrays:


<lang Haskell>import Data.Array
<syntaxhighlight lang="haskell">import Data.Array
mmult :: (Ix i, Num a) => Array (i,i) a -> Array (i,i) a -> Array (i,i) a
mmult :: (Ix i, Num a) => Array (i,i) a -> Array (i,i) a -> Array (i,i) a
Line 3,457: Line 3,457:
jr = range (y1,y1')
jr = range (y1,y1')
kr = range (x1,x1')
kr = range (x1,x1')
l = [((i,j), sum [x!(i,k) * y!(k,j) | k <- kr]) | i <- ir, j <- jr]</lang>
l = [((i,j), sum [x!(i,k) * y!(k,j) | k <- kr]) | i <- ir, j <- jr]</syntaxhighlight>
===With List and without transpose===
===With List and without transpose===
<lang Haskell>multiply :: Num a => [[a]] -> [[a]] -> [[a]]
<syntaxhighlight lang="haskell">multiply :: Num a => [[a]] -> [[a]] -> [[a]]
multiply us vs = map (mult [] vs) us
multiply us vs = map (mult [] vs) us
where
where
Line 3,476: Line 3,476:
multiply
multiply
[[1, 2], [3, 4]]
[[1, 2], [3, 4]]
[[-3, -8, 3], [-2, 1, 4]]</lang>
[[-3, -8, 3], [-2, 1, 4]]</syntaxhighlight>
{{out}}
{{out}}
<pre>[-7,-6,11]
<pre>[-7,-6,11]
Line 3,482: Line 3,482:


===With List and without transpose - shorter===
===With List and without transpose - shorter===
<lang Haskell>mult :: Num a => [[a]] -> [[a]] -> [[a]]
<syntaxhighlight lang="haskell">mult :: Num a => [[a]] -> [[a]] -> [[a]]
mult uss vss =
mult uss vss =
let go xs
let go xs
Line 3,492: Line 3,492:
main =
main =
mapM_ print $
mapM_ print $
mult [[1, 2], [3, 4]] [[-3, -8, 3], [-2, 1, 4]]</lang>
mult [[1, 2], [3, 4]] [[-3, -8, 3], [-2, 1, 4]]</syntaxhighlight>
{{out}}
{{out}}
<pre>[-7,-6,11]
<pre>[-7,-6,11]
Line 3,498: Line 3,498:


===With Numeric.LinearAlgebra===
===With Numeric.LinearAlgebra===
<lang Haskell>import Numeric.LinearAlgebra
<syntaxhighlight lang="haskell">import Numeric.LinearAlgebra


a, b :: Matrix I
a, b :: Matrix I
Line 3,506: Line 3,506:


main :: IO ()
main :: IO ()
main = print $ a <> b</lang>
main = print $ a <> b</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,514: Line 3,514:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>REAL :: m=4, n=2, p=3, a(m,n), b(n,p), res(m,p)
<syntaxhighlight lang="hicest">REAL :: m=4, n=2, p=3, a(m,n), b(n,p), res(m,p)


a = $ ! initialize to 1, 2, ..., m*n
a = $ ! initialize to 1, 2, ..., m*n
Line 3,528: Line 3,528:
ENDDO
ENDDO


DLG(DefWidth=4, Text=a, Text=b,Y=0, Text=res,Y=0)</lang>
DLG(DefWidth=4, Text=a, Text=b,Y=0, Text=res,Y=0)</syntaxhighlight>
<lang hicest>a b res
<syntaxhighlight lang="hicest">a b res
1 2 1 2 3 9 12 15
1 2 1 2 3 9 12 15
3 4 4 5 6 19 26 33
3 4 4 5 6 19 26 33
5 6 29 40 51
5 6 29 40 51
7 8 39 54 69 </lang>
7 8 39 54 69 </syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 3,539: Line 3,539:
Using the provided matrix library:
Using the provided matrix library:


<lang icon>
<syntaxhighlight lang="icon">
link matrix
link matrix


Line 3,553: Line 3,553:
write_matrix ("", m3)
write_matrix ("", m3)
end
end
</syntaxhighlight>
</lang>


And a hand-crafted multiply procedure:
And a hand-crafted multiply procedure:


<lang icon>
<syntaxhighlight lang="icon">
procedure multiply_matrix (m1, m2)
procedure multiply_matrix (m1, m2)
result := [] # to hold the final matrix
result := [] # to hold the final matrix
Line 3,573: Line 3,573:
return result
return result
end
end
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,591: Line 3,591:
=={{header|IDL}}==
=={{header|IDL}}==


<lang idl>result = arr1 # arr2</lang>
<syntaxhighlight lang="idl">result = arr1 # arr2</syntaxhighlight>


=={{header|Idris}}==
=={{header|Idris}}==
<lang idris>import Data.Vect
<syntaxhighlight lang="idris">import Data.Vect


Matrix : Nat -> Nat -> Type -> Type
Matrix : Nat -> Nat -> Type -> Type
Line 3,607: Line 3,607:
multiply' : Num t => Matrix m1 n t -> Matrix m2 n t -> Matrix m1 m2 t
multiply' : Num t => Matrix m1 n t -> Matrix m2 n t -> Matrix m1 m2 t
multiply' (a::as) b = map (dot a) b :: multiply' as b
multiply' (a::as) b = map (dot a) b :: multiply' as b
multiply' [] _ = []</lang>
multiply' [] _ = []</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Matrix multiply in J is <code>+/ .*</code>. For example:
Matrix multiply in J is <code>+/ .*</code>. For example:
<lang j> mp =: +/ .* NB. Matrix product
<syntaxhighlight lang="j"> mp =: +/ .* NB. Matrix product
A =: ^/~>:i. 4 NB. Same A as in other examples (1 1 1 1, 2 4 8 16, 3 9 27 81,:4 16 64 256)
A =: ^/~>:i. 4 NB. Same A as in other examples (1 1 1 1, 2 4 8 16, 3 9 27 81,:4 16 64 256)
Line 3,620: Line 3,620:
0.00 1.00 0.00 0.00
0.00 1.00 0.00 0.00
0.00 0.00 1.00 0.00
0.00 0.00 1.00 0.00
0.00 0.00 0.00 1.00</lang>
0.00 0.00 0.00 1.00</syntaxhighlight>
The notation is for a generalized inner product so that
The notation is for a generalized inner product so that
<lang j>x ~:/ .*. y NB. boolean inner product ( ~: is "not equal" (exclusive or) and *. is "and")
<syntaxhighlight lang="j">x ~:/ .*. y NB. boolean inner product ( ~: is "not equal" (exclusive or) and *. is "and")
x *./ .= y NB. which rows of x are the same as vector y?
x *./ .= y NB. which rows of x are the same as vector y?
x + / .= y NB. number of places where a value in row x equals the corresponding value in y</lang>
x + / .= y NB. number of places where a value in row x equals the corresponding value in y</syntaxhighlight>
[[Floyd-Warshall_algorithm#J|etc.]]
[[Floyd-Warshall_algorithm#J|etc.]]


Line 3,634: Line 3,634:


=={{header|Java}}==
=={{header|Java}}==
<lang java>public static double[][] mult(double a[][], double b[][]){//a[m][n], b[n][p]
<syntaxhighlight lang="java">public static double[][] mult(double a[][], double b[][]){//a[m][n], b[n][p]
if(a.length == 0) return new double[0][0];
if(a.length == 0) return new double[0][0];
if(a[0].length != b.length) return null; //invalid dims
if(a[0].length != b.length) return null; //invalid dims
Line 3,652: Line 3,652:
}
}
return ans;
return ans;
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 3,660: Line 3,660:


Extends [[Matrix Transpose#JavaScript]]
Extends [[Matrix Transpose#JavaScript]]
<lang javascript>// returns a new matrix
<syntaxhighlight lang="javascript">// returns a new matrix
Matrix.prototype.mult = function(other) {
Matrix.prototype.mult = function(other) {
if (this.width != other.height) {
if (this.width != other.height) {
Line 3,682: Line 3,682:
var a = new Matrix([[1,2],[3,4]])
var a = new Matrix([[1,2],[3,4]])
var b = new Matrix([[-3,-8,3],[-2,1,4]]);
var b = new Matrix([[-3,-8,3],[-2,1,4]]);
print(a.mult(b));</lang>
print(a.mult(b));</syntaxhighlight>
{{out}}
{{out}}
<pre>-7,-6,11
<pre>-7,-6,11
Line 3,688: Line 3,688:


====Functional====
====Functional====
<lang JavaScript>(function () {
<syntaxhighlight lang="javascript">(function () {
'use strict';
'use strict';


Line 3,754: Line 3,754:
}
}


})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<lang Javascript>[[51, -8, 26, -18], [-8, -38, -6, 34],
<syntaxhighlight lang="javascript">[[51, -8, 26, -18], [-8, -38, -6, 34],
[33, 42, 38, -14], [17, 74, 72, 44]]</lang>
[33, 42, 38, -14], [17, 74, 72, 44]]</syntaxhighlight>


===ES6===
===ES6===
<lang JavaScript>((() => {
<syntaxhighlight lang="javascript">((() => {
"use strict";
"use strict";


Line 3,850: Line 3,850:
// MAIN ---
// MAIN ---
return main();
return main();
}))();</lang>
}))();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[[51,-8,26,-18],[-8,-38,-6,34],[33,42,38,-14],[17,74,72,44]]</pre>
<pre>[[51,-8,26,-18],[-8,-38,-6,34],[33,42,38,-14],[17,74,72,44]]</pre>
Line 3,858: Line 3,858:


The function multiply(A;B) assumes its arguments are numeric matrices of the proper dimensions. Note that preallocating the resultant matrix would actually slow things down.
The function multiply(A;B) assumes its arguments are numeric matrices of the proper dimensions. Note that preallocating the resultant matrix would actually slow things down.
<lang jq>def dot_product(a; b):
<syntaxhighlight lang="jq">def dot_product(a; b):
a as $a | b as $b
a as $a | b as $b
| reduce range(0;$a|length) as $i (0; . + ($a[$i] * $b[$i]) );
| reduce range(0;$a|length) as $i (0; . + ($a[$i] * $b[$i]) );
Line 3,875: Line 3,875:
| reduce range(0; $A|length) as $i
| reduce range(0; $A|length) as $i
([]; reduce range(0; $p) as $j
([]; reduce range(0; $p) as $j
(.; .[$i][$j] = dot_product( $A[$i]; $BT[$j] ) )) ;</lang>
(.; .[$i][$j] = dot_product( $A[$i]; $BT[$j] ) )) ;</syntaxhighlight>
'''Example'''
'''Example'''
((2|sqrt)/2) as $r | [ [$r, $r], [(-($r)), $r]] as $R
((2|sqrt)/2) as $r | [ [$r, $r], [(-($r)), $r]] as $R
Line 3,887: Line 3,887:
Uses module listed in [[Matrix Transpose#Jsish]]
Uses module listed in [[Matrix Transpose#Jsish]]


<lang javascript>/* Matrix multiplication, in Jsish */
<syntaxhighlight lang="javascript">/* Matrix multiplication, in Jsish */
require('Matrix');
require('Matrix');


Line 3,904: Line 3,904:
a.mult(b) ==> { height:2, mtx:[ [ -7, -6, 11 ], [ -17, -20, 25 ] ], width:3 }
a.mult(b) ==> { height:2, mtx:[ [ -7, -6, 11 ], [ -17, -20, 25 ] ], width:3 }
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 3,912: Line 3,912:
=={{header|Julia}}==
=={{header|Julia}}==
The multiplication is denoted by *
The multiplication is denoted by *
<lang Julia>julia> [1 2 3 ; 4 5 6] * [1 2 ; 3 4 ; 5 6] # product of a 2x3 by a 3x2
<syntaxhighlight lang="julia">julia> [1 2 3 ; 4 5 6] * [1 2 ; 3 4 ; 5 6] # product of a 2x3 by a 3x2
2x2 Array{Int64,2}:
2x2 Array{Int64,2}:
22 28
22 28
Line 3,920: Line 3,920:
1-element Array{Int64,1}:
1-element Array{Int64,1}:
14
14
</syntaxhighlight>
</lang>


=={{header|K}}==
=={{header|K}}==
<lang k> (1 2;3 4)_mul (5 6;7 8)
<syntaxhighlight lang="k"> (1 2;3 4)_mul (5 6;7 8)
(19 22
(19 22
43 50)</lang>
43 50)</syntaxhighlight>


=={{header|Klong}}==
=={{header|Klong}}==
<lang k> mul::{[a b];b::+y;{a::x;+/'{a*x}'b}'x}
<syntaxhighlight lang="k"> mul::{[a b];b::+y;{a::x;+/'{a*x}'b}'x}
[[1 2] [3 4]] mul [[5 6] [7 8]]
[[1 2] [3 4]] mul [[5 6] [7 8]]
[[19 22]
[[19 22]
[43 50]]</lang>
[43 50]]</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.3
<syntaxhighlight lang="scala">// version 1.1.3


typealias Vector = DoubleArray
typealias Vector = DoubleArray
Line 3,973: Line 3,973:
)
)
printMatrix(m1 * m2)
printMatrix(m1 * m2)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,985: Line 3,985:
=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==


<lang scheme>
<syntaxhighlight lang="scheme">
{require lib_matrix}
{require lib_matrix}


Line 4,008: Line 4,008:
[ 66, 81,-12],
[ 66, 81,-12],
[-24,-18,150]]
[-24,-18,150]]
</syntaxhighlight>
</lang>


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang Lang5>[[1 2 3] [4 5 6]] 'm dress
<syntaxhighlight lang="lang5">[[1 2 3] [4 5 6]] 'm dress
[[1 2] [3 4] [5 6]] 'm dress * .</lang>
[[1 2] [3 4] [5 6]] 'm dress * .</syntaxhighlight>
{{out}}
{{out}}
<pre>[
<pre>[
Line 4,023: Line 4,023:
Use the LFE <code>transpose/1</code> function from [[Matrix transposition]].
Use the LFE <code>transpose/1</code> function from [[Matrix transposition]].


<lang lisp>
<syntaxhighlight lang="lisp">
(defun matrix* (matrix-1 matrix-2)
(defun matrix* (matrix-1 matrix-2)
(list-comp
(list-comp
Line 4,031: Line 4,031:
(lists:foldl #'+/2 0
(lists:foldl #'+/2 0
(lists:zipwith #'*/2 a b)))))
(lists:zipwith #'*/2 a b)))))
</syntaxhighlight>
</lang>


Usage example in the LFE REPL:
Usage example in the LFE REPL:


<lang lisp>
<syntaxhighlight lang="lisp">
> (set ma '((1 2)
> (set ma '((1 2)
(3 4)
(3 4)
Line 4,045: Line 4,045:
> (matrix* ma mb)
> (matrix* ma mb)
((5 11 17 23) (11 25 39 53) (17 39 61 83) (23 53 83 113))
((5 11 17 23) (11 25 39 53) (17 39 61 83) (23 53 83 113))
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
There is no native matrix capability. A set of functions is available at http://www.diga.me.uk/RCMatrixFuncs.bas implementing matrices of arbitrary dimension in a string format.
There is no native matrix capability. A set of functions is available at http://www.diga.me.uk/RCMatrixFuncs.bas implementing matrices of arbitrary dimension in a string format.
<syntaxhighlight lang="lb">
<lang lb>
MatrixA$ ="4, 4, 1, 1, 1, 1, 2, 4, 8, 16, 3, 9, 27, 81, 4, 16, 64, 256"
MatrixA$ ="4, 4, 1, 1, 1, 1, 2, 4, 8, 16, 3, 9, 27, 81, 4, 16, 64, 256"
MatrixB$ ="4, 4, 4, -3, 4/3, -1/4 , -13/3, 19/4, -7/3, 11/24, 3/2, -2, 7/6, -1/4, -1/6, 1/4, -1/6, 1/24"
MatrixB$ ="4, 4, 4, -3, 4/3, -1/4 , -13/3, 19/4, -7/3, 11/24, 3/2, -2, 7/6, -1/4, -1/6, 1/4, -1/6, 1/24"
Line 4,060: Line 4,060:
MatrixP$ =MatrixMultiply$( MatrixA$, MatrixB$)
MatrixP$ =MatrixMultiply$( MatrixA$, MatrixB$)
call DisplayMatrix MatrixP$
call DisplayMatrix MatrixP$
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 4,082: Line 4,082:


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>TO LISTVMD :A :F :C :NV
<syntaxhighlight lang="logo">TO LISTVMD :A :F :C :NV
;PROCEDURE LISTVMD
;PROCEDURE LISTVMD
;A = LIST
;A = LIST
Line 4,186: Line 4,186:
THIS_IS: 5 ROWS X 5 COLS
THIS_IS: 5 ROWS X 5 COLS
{{830 1880 2930 3980 5030} {890 2040 3190 4340 5490} {950 2200 3450 4700 5950}
{{830 1880 2930 3980 5030} {890 2040 3190 4340 5490} {950 2200 3450 4700 5950}
{1010 2360 3710 5060 6410} {1070 2520 3970 5420 6870}}</lang>
{1010 2360 3710 5060 6410} {1070 2520 3970 5420 6870}}</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function MatMul( m1, m2 )
<syntaxhighlight lang="lua">function MatMul( m1, m2 )
if #m1[1] ~= #m2 then -- inner matrix-dimensions must agree
if #m1[1] ~= #m2 then -- inner matrix-dimensions must agree
return nil
return nil
Line 4,219: Line 4,219:
end
end
io.write("\n")
io.write("\n")
end </lang>
end </syntaxhighlight>


===SciLua===
===SciLua===
Using the sci.alg library from scilua.org
Using the sci.alg library from scilua.org
<lang Lua>local alg = require("sci.alg")
<syntaxhighlight lang="lua">local alg = require("sci.alg")
mat1 = alg.tomat{{1, 2, 3}, {4, 5, 6}}
mat1 = alg.tomat{{1, 2, 3}, {4, 5, 6}}
mat2 = alg.tomat{{1, 2}, {3, 4}, {5, 6}}
mat2 = alg.tomat{{1, 2}, {3, 4}, {5, 6}}
mat3 = mat1[] ** mat2[]
mat3 = mat1[] ** mat2[]
print(mat3)</lang>
print(mat3)</syntaxhighlight>
{{out}}
{{out}}
<pre>+22.00000,+28.00000
<pre>+22.00000,+28.00000
Line 4,233: Line 4,233:


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckMatMult {
Module CheckMatMult {
\\ Matrix Multiplication
\\ Matrix Multiplication
Line 4,301: Line 4,301:
}
}
CheckMatMult2
CheckMatMult2
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 4,312: Line 4,312:


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>A := <<1|2|3>,<4|5|6>>;
<syntaxhighlight lang="maple">A := <<1|2|3>,<4|5|6>>;


B := <<1,2,3>|<4,5,6>|<7,8,9>|<10,11,12>>;
B := <<1,2,3>|<4,5,6>|<7,8,9>|<10,11,12>>;


A . B;</lang>
A . B;</syntaxhighlight>
{{out}}
{{out}}
<pre> [1 2 3]
<pre> [1 2 3]
Line 4,333: Line 4,333:


=={{header|MathCortex}}==
=={{header|MathCortex}}==
<lang mathcortex>
<syntaxhighlight lang="mathcortex">
>> A = [2,3; -2,1]
>> A = [2,3; -2,1]
2 3
2 3
Line 4,345: Line 4,345:
14 10
14 10
2 -2
2 -2
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Line 4,353: Line 4,353:
This computes a dot product:
This computes a dot product:


<lang mathematica>Dot[{{a, b}, {c, d}}, {{w, x}, {y, z}}]</lang>
<syntaxhighlight lang="mathematica">Dot[{{a, b}, {c, d}}, {{w, x}, {y, z}}]</syntaxhighlight>


With the following output:
With the following output:


<lang mathematica>{{a w + b y, a x + b z}, {c w + d y, c x + d z}}</lang>
<syntaxhighlight lang="mathematica">{{a w + b y, a x + b z}, {c w + d y, c x + d z}}</syntaxhighlight>


This also computes a dot product, using the infix . notation:
This also computes a dot product, using the infix . notation:


<lang mathematica>{{a, b}, {c, d}} . {{w, x}, {y, z}}</lang>
<syntaxhighlight lang="mathematica">{{a, b}, {c, d}} . {{w, x}, {y, z}}</syntaxhighlight>


This does element-wise multiplication of matrices:
This does element-wise multiplication of matrices:


<lang mathematica>Times[{{a, b}, {c, d}}, {{w, x}, {y, z}}]</lang>
<syntaxhighlight lang="mathematica">Times[{{a, b}, {c, d}}, {{w, x}, {y, z}}]</syntaxhighlight>


With the following output:
With the following output:


<lang mathematica>{{a w, b x}, {c y, d z}}</lang>
<syntaxhighlight lang="mathematica">{{a w, b x}, {c y, d z}}</syntaxhighlight>


Alternative infix notations '*' and ' ' (space, indicating multiplication):
Alternative infix notations '*' and ' ' (space, indicating multiplication):


<lang mathematica>{{a, b}, {c, d}}*{{w, x}, {y, z}}</lang>
<syntaxhighlight lang="mathematica">{{a, b}, {c, d}}*{{w, x}, {y, z}}</syntaxhighlight>
<lang mathematica>{{a, b}, {c, d}} {{w, x}, {y, z}}</lang>
<syntaxhighlight lang="mathematica">{{a, b}, {c, d}} {{w, x}, {y, z}}</syntaxhighlight>


In all cases matrices can be fully symbolic or numeric or mixed symbolic and numeric.
In all cases matrices can be fully symbolic or numeric or mixed symbolic and numeric.
Line 4,380: Line 4,380:
as complex numbers:
as complex numbers:


<lang mathematica>Dot[{{85, 60, 65}, {54, 99, 33}, {46, 52, 87}}, {{89, 77, 98}, {55, 27, 25}, {80, 68, 85}}]</lang>
<syntaxhighlight lang="mathematica">Dot[{{85, 60, 65}, {54, 99, 33}, {46, 52, 87}}, {{89, 77, 98}, {55, 27, 25}, {80, 68, 85}}]</syntaxhighlight>


With the following output:
With the following output:


<lang mathematica>{{16065, 12585, 15355}, {12891, 9075, 10572}, {13914, 10862, 13203}}</lang>
<syntaxhighlight lang="mathematica">{{16065, 12585, 15355}, {12891, 9075, 10572}, {13914, 10862, 13203}}</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
Matlab contains two methods of multiplying matrices: by using the "mtimes(matrix,matrix)" function, or the "*" operator.
Matlab contains two methods of multiplying matrices: by using the "mtimes(matrix,matrix)" function, or the "*" operator.


<lang MATLAB>>> A = [1 2;3 4]
<syntaxhighlight lang="matlab">>> A = [1 2;3 4]


A =
A =
Line 4,415: Line 4,415:


19 22
19 22
43 50</lang>
43 50</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>a: matrix([1, 2],
<syntaxhighlight lang="maxima">a: matrix([1, 2],
[3, 4],
[3, 4],
[5, 6],
[5, 6],
Line 4,430: Line 4,430:
[19, 26, 33],
[19, 26, 33],
[29, 40, 51],
[29, 40, 51],
[39, 54, 69]) */</lang>
[39, 54, 69]) */</syntaxhighlight>


=={{header|Nial}}==
=={{header|Nial}}==
<lang nial>|A := 4 4 reshape 1 1 1 1 2 4 8 16 3 9 27 81 4 16 64 256
<syntaxhighlight lang="nial">|A := 4 4 reshape 1 1 1 1 2 4 8 16 3 9 27 81 4 16 64 256
=1 1 1 1
=1 1 1 1
=2 4 8 16
=2 4 8 16
Line 4,444: Line 4,444:
=1.3e-15 1. -4.4e-16 -3.3e-16
=1.3e-15 1. -4.4e-16 -3.3e-16
=0. 0. 1. 4.4e-16
=0. 0. 1. 4.4e-16
=0. 0. 0. 1.</lang>
=0. 0. 0. 1.</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
{{libheader|strfmt}}
{{libheader|strfmt}}
<lang nim>import strfmt
<syntaxhighlight lang="nim">import strfmt


type Matrix[M, N: static[int]] = array[M, array[N, float]]
type Matrix[M, N: static[int]] = array[M, array[N, float]]
Line 4,478: Line 4,478:
echo b
echo b
echo a * b
echo a * b
echo b * a</lang>
echo b * a</syntaxhighlight>


{{out}}
{{out}}
Line 4,501: Line 4,501:


This version works on arrays of arrays of ints:
This version works on arrays of arrays of ints:
<lang ocaml>let matrix_multiply x y =
<syntaxhighlight lang="ocaml">let matrix_multiply x y =
let x0 = Array.length x
let x0 = Array.length x
and y0 = Array.length y in
and y0 = Array.length y in
Line 4,513: Line 4,513:
done
done
done;
done;
z</lang>
z</syntaxhighlight>


# matrix_multiply [|[|1;2|];[|3;4|]|] [|[|-3;-8;3|];[|-2;1;4|]|];;
# matrix_multiply [|[|1;2|];[|3;4|]|] [|[|-3;-8;3|];[|-2;1;4|]|];;
Line 4,520: Line 4,520:
{{trans|Scheme}}
{{trans|Scheme}}
This version works on lists of lists of ints:
This version works on lists of lists of ints:
<lang ocaml>(* equivalent to (apply map ...) *)
<syntaxhighlight lang="ocaml">(* equivalent to (apply map ...) *)
let rec mapn f lists =
let rec mapn f lists =
assert (lists <> []);
assert (lists <> []);
Line 4,536: Line 4,536:
(List.map2 ( * ) row column))
(List.map2 ( * ) row column))
m2)
m2)
m1</lang>
m1</syntaxhighlight>


# matrix_multiply [[1;2];[3;4]] [[-3;-8;3];[-2;1;4]];;
# matrix_multiply [[1;2];[3;4]] [[-3;-8;3];[-2;1;4]];;
Line 4,542: Line 4,542:


=={{header|Octave}}==
=={{header|Octave}}==
<lang octave>a = zeros(4);
<syntaxhighlight lang="octave">a = zeros(4);
% prepare the matrix
% prepare the matrix
% 1 1 1 1
% 1 1 1 1
Line 4,554: Line 4,554:
endfor
endfor
b = inverse(a);
b = inverse(a);
a * b</lang>
a * b</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
This short version works on lists of lists length less than 253 rows and less than 253 columns.
This short version works on lists of lists length less than 253 rows and less than 253 columns.
<lang scheme>; short version based on 'apply'
<syntaxhighlight lang="scheme">; short version based on 'apply'
(define (matrix-multiply matrix1 matrix2)
(define (matrix-multiply matrix1 matrix2)
(map
(map
Line 4,567: Line 4,567:
matrix2))
matrix2))
matrix1))
matrix1))
</syntaxhighlight>
</lang>


> (matrix-multiply '((1 2) (3 4)) '((-3 -8 3) (-2 1 4)))
> (matrix-multiply '((1 2) (3 4)) '((-3 -8 3) (-2 1 4)))
Line 4,573: Line 4,573:


This long version works on lists of lists with any matrix dimensions.
This long version works on lists of lists with any matrix dimensions.
<lang scheme>; long version based on recursive cycles
<syntaxhighlight lang="scheme">; long version based on recursive cycles
(define (matrix-multiply A B)
(define (matrix-multiply A B)
(define m (length A))
(define m (length A))
Line 4,601: Line 4,601:
r))))
r))))
rows)))))
rows)))))
</syntaxhighlight>
</lang>


Testing large matrices:
Testing large matrices:
<lang scheme>; [372x17] * [17x372]
<syntaxhighlight lang="scheme">; [372x17] * [17x372]
(define M 372)
(define M 372)
(define N 17)
(define N 17)
Line 4,627: Line 4,627:


(for-each print (matrix-multiply A B))
(for-each print (matrix-multiply A B))
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,651: Line 4,651:
=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
Generic MatMul:
Generic MatMul:
<lang>
<syntaxhighlight lang="text">
'generic with striding pointers
'generic with striding pointers
'def typ float
'def typ float
Line 4,680: Line 4,680:
next
next
end function
end function
</syntaxhighlight>
</lang>


When using matrices in Video graphics, speed is important. Here is a matrix multiplier written in OxygenBasics's x86 Assembly code.
When using matrices in Video graphics, speed is important. Here is a matrix multiplier written in OxygenBasics's x86 Assembly code.
<lang oxygenbasic>
<syntaxhighlight lang="oxygenbasic">
'Example of matrix layout mapped to an array of 4x4 cells
'Example of matrix layout mapped to an array of 4x4 cells
'
'
Line 4,797: Line 4,797:


Print ShowMatrix C,n
Print ShowMatrix C,n
</lang>
</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>M*N</lang>
<syntaxhighlight lang="parigp">M*N</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
Line 4,807: Line 4,807:
This function takes two references to arrays of arrays and returns the product as a reference to a new anonymous array of arrays.
This function takes two references to arrays of arrays and returns the product as a reference to a new anonymous array of arrays.


<lang perl>sub mmult
<syntaxhighlight lang="perl">sub mmult
{
{
our @a; local *a = shift;
our @a; local *a = shift;
Line 4,841: Line 4,841:


$c = mmult(\@a,\@b);
$c = mmult(\@a,\@b);
display($c)</lang>
display($c)</syntaxhighlight>
{{out}}
{{out}}
<pre> -7 -6 11
<pre> -7 -6 11
Line 4,847: Line 4,847:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">matrix_mul</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">matrix_mul</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
Line 4,907: Line 4,907:
<span style="color: #000000;">K</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #000000;">row</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">371</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">),</span><span style="color: #000000;">16</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">K</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #000000;">row</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">371</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">),</span><span style="color: #000000;">16</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">matrix_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">J</span><span style="color: #0000FF;">,</span><span style="color: #000000;">K</span><span style="color: #0000FF;">),{</span><span style="color: #008000;">""</span><span style="color: #0000FF;">},</span><span style="color: #000000;">2</span><span style="color: #0000FF;">}),</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">matrix_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">J</span><span style="color: #0000FF;">,</span><span style="color: #000000;">K</span><span style="color: #0000FF;">),{</span><span style="color: #008000;">""</span><span style="color: #0000FF;">},</span><span style="color: #000000;">2</span><span style="color: #0000FF;">}),</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 4,934: Line 4,934:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de matMul (Mat1 Mat2)
<syntaxhighlight lang="picolisp">(de matMul (Mat1 Mat2)
(mapcar
(mapcar
'((Row)
'((Row)
Line 4,943: Line 4,943:
(matMul
(matMul
'((1 2 3) (4 5 6))
'((1 2 3) (4 5 6))
'((6 -1) (3 2) (0 -3)) )</lang>
'((6 -1) (3 2) (0 -3)) )</syntaxhighlight>
{{out}}
{{out}}
<pre>-> ((12 -6) (39 -12))</pre>
<pre>-> ((12 -6) (39 -12))</pre>


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Matrix multiplication of A by B, yielding C */
/* Matrix multiplication of A by B, yielding C */
MMULT: procedure (a, b, c);
MMULT: procedure (a, b, c);
Line 4,972: Line 4,972:
end;
end;
end MMULT;
end MMULT;
</syntaxhighlight>
</lang>


=={{header|Pop11}}==
=={{header|Pop11}}==


<lang pop11>define matmul(a, b) -> c;
<syntaxhighlight lang="pop11">define matmul(a, b) -> c;
lvars ba = boundslist(a), bb = boundslist(b);
lvars ba = boundslist(a), bb = boundslist(b);
lvars i, i0 = ba(1), i1 = ba(2);
lvars i, i0 = ba(1), i1 = ba(2);
Line 4,998: Line 4,998:
endfor;
endfor;
endfor;
endfor;
enddefine;</lang>
enddefine;</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function multarrays($a, $b) {
function multarrays($a, $b) {
$n,$m,$p = ($a.Count - 1), ($b.Count - 1), ($b[0].Count - 1)
$n,$m,$p = ($a.Count - 1), ($b.Count - 1), ($b[0].Count - 1)
Line 5,035: Line 5,035:
"`$a * `$c ="
"`$a * `$c ="
show (multarrays $a $c)
show (multarrays $a $c)
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 5,062: Line 5,062:
{{trans|Scheme}}
{{trans|Scheme}}
{{works with|SWI Prolog|5.9.9}}
{{works with|SWI Prolog|5.9.9}}
<lang prolog>% SWI-Prolog has transpose/2 in its clpfd library
<syntaxhighlight lang="prolog">% SWI-Prolog has transpose/2 in its clpfd library
:- use_module(library(clpfd)).
:- use_module(library(clpfd)).


Line 5,072: Line 5,072:
% as lists of lists. M3 is the product of M1 and M2
% as lists of lists. M3 is the product of M1 and M2
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).</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
Matrices represented as integer arrays with rows in the first dimension and columns in the second.
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))
<syntaxhighlight lang="purebasic">Procedure multiplyMatrix(Array a(2), Array b(2), Array prd(2))
Protected ar = ArraySize(a()) ;#rows for matrix a
Protected ar = ArraySize(a()) ;#rows for matrix a
Protected ac = ArraySize(a(), 2) ;#cols for matrix a
Protected ac = ArraySize(a(), 2) ;#cols for matrix a
Line 5,098: Line 5,098:
ProcedureReturn #False ;multiplication not performed, dimensions invalid
ProcedureReturn #False ;multiplication not performed, dimensions invalid
EndIf
EndIf
EndProcedure</lang>
EndProcedure</syntaxhighlight>
Additional code to demonstrate use.
Additional code to demonstrate use.
<lang PureBasic>DataSection
<syntaxhighlight lang="purebasic">DataSection
Data.i 2,3 ;matrix a (#rows, #cols)
Data.i 2,3 ;matrix a (#rows, #cols)
Data.i 1,2,3, 4,5,6 ;elements by row
Data.i 1,2,3, 4,5,6 ;elements by row
Line 5,153: Line 5,153:
Input()
Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
{{out}}
{{out}}
<pre>matrix a: (2, 3)
<pre>matrix a: (2, 3)
Line 5,169: Line 5,169:


=={{header|Python}}==
=={{header|Python}}==
<lang python>a=((1, 1, 1, 1), # matrix A #
<syntaxhighlight lang="python">a=((1, 1, 1, 1), # matrix A #
(2, 4, 8, 16),
(2, 4, 8, 16),
(3, 9, 27, 81),
(3, 9, 27, 81),
Line 5,206: Line 5,206:
print '%8.2f '%val,
print '%8.2f '%val,
print ']'
print ']'
print ')'</lang>
print ')'</syntaxhighlight>


Another one, {{trans|Scheme}}
Another one, {{trans|Scheme}}
<lang python>from operator import mul
<syntaxhighlight lang="python">from operator import mul


def matrixMul(m1, m2):
def matrixMul(m1, m2):
Line 5,218: Line 5,218:
sum(map(mul, row, column)),
sum(map(mul, row, column)),
*m2),
*m2),
m1)</lang>
m1)</syntaxhighlight>


Using list comprehensions, multiplying matrices represented as lists of lists. (Input is not validated):
Using list comprehensions, multiplying matrices represented as lists of lists. (Input is not validated):
<lang python>def mm(A, B):
<syntaxhighlight lang="python">def mm(A, B):
return [[sum(x * B[i][col] for i,x in enumerate(row)) for col in range(len(B[0]))] for row in A]</lang>
return [[sum(x * B[i][col] for i,x in enumerate(row)) for col in range(len(B[0]))] for row in A]</syntaxhighlight>


Another one, use numpy the most popular array package for python
Another one, use numpy the most popular array package for python
<lang python>
<syntaxhighlight lang="python">
import numpy as np
import numpy as np
np.dot(a,b)
np.dot(a,b)
#or if a is an array
#or if a is an array
a.dot(b)</lang>
a.dot(b)</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
<lang r>a %*% b</lang>
<syntaxhighlight lang="r">a %*% b</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
{{trans|Scheme}}
{{trans|Scheme}}


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(define (m-mult m1 m2)
(define (m-mult m1 m2)
Line 5,245: Line 5,245:
(m-mult '((1 2) (3 4)) '((5 6) (7 8)))
(m-mult '((1 2) (3 4)) '((5 6) (7 8)))
;; -> '((19 22) (43 50))
;; -> '((19 22) (43 50))
</syntaxhighlight>
</lang>


Alternative:
Alternative:
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(require math)
(require math)
(matrix* (matrix [[1 2] [3 4]]) (matrix [[5 6] [7 8]]))
(matrix* (matrix [[1 2] [3 4]]) (matrix [[5 6] [7 8]]))
;; -> (array #[#[19 22] #[43 50]])
;; -> (array #[#[19 22] #[43 50]])
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 5,275: Line 5,275:
used on an array to generate all the indexes of the array. We have a way of indicating a range by the infix <tt>..</tt> operator, and you can put a <tt>^</tt> on either end to exclude that endpoint. We found ourselves writing <tt>0 ..^ @a</tt> so often that we made <tt>^@a</tt> a shorthand for that. It's pronounced "upto". The array is evaluated in a numeric context, so it returns the number of elements it contains, which is exactly what you want for the exclusive limit of the range.
used on an array to generate all the indexes of the array. We have a way of indicating a range by the infix <tt>..</tt> operator, and you can put a <tt>^</tt> on either end to exclude that endpoint. We found ourselves writing <tt>0 ..^ @a</tt> so often that we made <tt>^@a</tt> a shorthand for that. It's pronounced "upto". The array is evaluated in a numeric context, so it returns the number of elements it contains, which is exactly what you want for the exclusive limit of the range.


<lang perl6>sub mmult(@a,@b) {
<syntaxhighlight lang="raku" line>sub mmult(@a,@b) {
my @p;
my @p;
for ^@a X ^@b[0] -> ($r, $c) {
for ^@a X ^@b[0] -> ($r, $c) {
Line 5,293: Line 5,293:
[ -1/6, 1/4, -1/6, 1/24];
[ -1/6, 1/4, -1/6, 1/24];


.say for mmult(@a,@b);</lang>
.say for mmult(@a,@b);</syntaxhighlight>


{{out}}
{{out}}
Line 5,307: Line 5,307:
Some people will find this more readable and elegant, and others will, well, not.
Some people will find this more readable and elegant, and others will, well, not.


<lang perl6>sub mmult(\a,\b) {
<syntaxhighlight lang="raku" line>sub mmult(\a,\b) {
[
[
for ^a -> \r {
for ^a -> \r {
Line 5,317: Line 5,317:
}
}
]
]
}</lang>
}</syntaxhighlight>


Here we use Z with an "op" of <tt>*</tt>, which is a zip with multiply. This, along with the <tt>[+]</tt> reduction operator, replaces the inner loop. We chose to split the outer X loop back into two loops to make it convenient to collect each subarray value in <tt>[...]</tt>. It just collects all the returned values from the inner loop and makes an array of them. The outer loop simply returns the outer array.
Here we use Z with an "op" of <tt>*</tt>, which is a zip with multiply. This, along with the <tt>[+]</tt> reduction operator, replaces the inner loop. We chose to split the outer X loop back into two loops to make it convenient to collect each subarray value in <tt>[...]</tt>. It just collects all the returned values from the inner loop and makes an array of them. The outer loop simply returns the outer array.
Line 5,323: Line 5,323:
For conciseness, the above could be written as:
For conciseness, the above could be written as:


<lang perl6>multi infix:<×> (@A, @B) {
<syntaxhighlight lang="raku" line>multi infix:<×> (@A, @B) {
@A.map: -> @a { do [+] @a Z× @B[*;$_] for ^@B[0] }
@A.map: -> @a { do [+] @a Z× @B[*;$_] for ^@B[0] }
}</lang>
}</syntaxhighlight>


Which overloads the built-in <code>×</code> operator for <code>Positional</code> operands. You’ll notice we are using <code>×</code> inside of the definition; since the arguments there are <code>Scalar</code>, it multiplies two numbers. Also, <code>do</code> is an alternative to parenthesising the loop for getting its result.
Which overloads the built-in <code>×</code> operator for <code>Positional</code> operands. You’ll notice we are using <code>×</code> inside of the definition; since the arguments there are <code>Scalar</code>, it multiplies two numbers. Also, <code>do</code> is an alternative to parenthesising the loop for getting its result.


=={{header|Rascal}}==
=={{header|Rascal}}==
<lang Rascal>public rel[real, real, real] matrixMultiplication(rel[real x, real y, real v] matrix1, rel[real x, real y, real v] matrix2){
<syntaxhighlight lang="rascal">public rel[real, real, real] matrixMultiplication(rel[real x, real y, real v] matrix1, rel[real x, real y, real v] matrix2){
if (max(matrix1.x) == max(matrix2.y)){
if (max(matrix1.x) == max(matrix2.y)){
p = {<x1,y1,x2,y2, v1*v2> | <x1,y1,v1> <- matrix1, <x2,y2,v2> <- matrix2};
p = {<x1,y1,x2,y2, v1*v2> | <x1,y1,v1> <- matrix1, <x2,y2,v2> <- matrix2};
Line 5,350: Line 5,350:
<1.0,0.0,-51.0>, <1.0,1.0,167.0>, <1.0,2.0,24.0>,
<1.0,0.0,-51.0>, <1.0,1.0,167.0>, <1.0,2.0,24.0>,
<2.0,0.0,4.0>, <2.0,1.0,-68.0>, <2.0,2.0,-41.0>
<2.0,0.0,4.0>, <2.0,1.0,-68.0>, <2.0,2.0,-41.0>
};</lang>
};</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program multiplies two matrices together, displays the matrices and the results. */
<syntaxhighlight lang="rexx">/*REXX program multiplies two matrices together, displays the matrices and the results. */
x.=; x.1= 1 2 /*╔═══════════════════════════════════╗*/
x.=; x.1= 1 2 /*╔═══════════════════════════════════╗*/
x.2= 3 4 /*║ As none of the matrix values have ║*/
x.2= 3 4 /*║ As none of the matrix values have ║*/
Line 5,386: Line 5,386:
do r=1 for rows; _= ' '
do r=1 for rows; _= ' '
do c=1 for cols; _= _ right( value(mat'.'r"."c), w); end; say _
do c=1 for cols; _= _ right( value(mat'.'r"."c), w); end; say _
end /*r*/; return</lang>
end /*r*/; return</syntaxhighlight>
{{out|output|text=&nbsp; when using the internal default input:}}
{{out|output|text=&nbsp; when using the internal default input:}}
<pre>
<pre>
Line 5,407: Line 5,407:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
load "stdlib.ring"
load "stdlib.ring"
n = 3
n = 3
Line 5,426: Line 5,426:
see nl
see nl
next
next
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 5,436: Line 5,436:
=={{header|Ruby}}==
=={{header|Ruby}}==
Using 'matrix' from the standard library:
Using 'matrix' from the standard library:
<lang ruby>require 'matrix'
<syntaxhighlight lang="ruby">require 'matrix'


Matrix[[1, 2],
Matrix[[1, 2],
[3, 4]] * Matrix[[-3, -8, 3],
[3, 4]] * Matrix[[-3, -8, 3],
[-2, 1, 4]]</lang>
[-2, 1, 4]]</syntaxhighlight>
{{out}}
{{out}}
Matrix[[-7, -6, 11], [-17, -20, 25]]
Matrix[[-7, -6, 11], [-17, -20, 25]]


Version for lists: {{trans|Haskell}}
Version for lists: {{trans|Haskell}}
<lang ruby>def matrix_mult(a, b)
<syntaxhighlight lang="ruby">def matrix_mult(a, b)
a.map do |ar|
a.map do |ar|
b.transpose.map { |bc| ar.zip(bc).map{ |x| x.inject(&:*) }.sum }
b.transpose.map { |bc| ar.zip(bc).map{ |x| x.inject(&:*) }.sum }
end
end
end</lang>
end</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>
<syntaxhighlight lang="rust">
struct Matrix {
struct Matrix {
dat: [[f32; 3]; 3]
dat: [[f32; 3]; 3]
Line 5,512: Line 5,512:
}
}


</syntaxhighlight>
</lang>


=={{header|S-lang}}==
=={{header|S-lang}}==
<lang C>% Matrix multiplication is a built-in with the S-Lang octothorpe operator.
<syntaxhighlight lang="c">% Matrix multiplication is a built-in with the S-Lang octothorpe operator.
variable A = [1,2,3,4,5,6];
variable A = [1,2,3,4,5,6];
reshape(A, [2,3]); % reshape 1d array to 2 rows, 3 columns
reshape(A, [2,3]); % reshape 1d array to 2 rows, 3 columns
Line 5,530: Line 5,530:
reshape(B, [2,3]);
reshape(B, [2,3]);
printf("\nA * B is %S (with reshaped B to match A)\n", A*B);
printf("\nA * B is %S (with reshaped B to match A)\n", A*B);
print(A*B);</lang>
print(A*B);</syntaxhighlight>


{{out}}
{{out}}
Line 5,555: Line 5,555:
Assuming an array of arrays representation:
Assuming an array of arrays representation:


<lang scala>def mult[A](a: Array[Array[A]], b: Array[Array[A]])(implicit n: Numeric[A]) = {
<syntaxhighlight lang="scala">def mult[A](a: Array[Array[A]], b: Array[Array[A]])(implicit n: Numeric[A]) = {
import n._
import n._
for (row <- a)
for (row <- a)
yield for(col <- b.transpose)
yield for(col <- b.transpose)
yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
}</lang>
}</syntaxhighlight>


For any subclass of <code>Seq</code> (which does not include Java-specific arrays):
For any subclass of <code>Seq</code> (which does not include Java-specific arrays):


<lang scala>def mult[A, CC[X] <: Seq[X], DD[Y] <: Seq[Y]](a: CC[DD[A]], b: CC[DD[A]])
<syntaxhighlight lang="scala">def mult[A, CC[X] <: Seq[X], DD[Y] <: Seq[Y]](a: CC[DD[A]], b: CC[DD[A]])
(implicit n: Numeric[A]): CC[DD[A]] = {
(implicit n: Numeric[A]): CC[DD[A]] = {
import n._
import n._
Line 5,570: Line 5,570:
yield for(col <- b.transpose)
yield for(col <- b.transpose)
yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
}</lang>
}</syntaxhighlight>


Examples:
Examples:
Line 5,600: Line 5,600:
{{trans|Common Lisp}}
{{trans|Common Lisp}}
This version works on lists of lists:
This version works on lists of lists:
<lang scheme>(define (matrix-multiply matrix1 matrix2)
<syntaxhighlight lang="scheme">(define (matrix-multiply matrix1 matrix2)
(map
(map
(lambda (row)
(lambda (row)
Line 5,607: Line 5,607:
(apply + (map * row column)))
(apply + (map * row column)))
matrix2))
matrix2))
matrix1))</lang>
matrix1))</syntaxhighlight>


> (matrix-multiply '((1 2) (3 4)) '((-3 -8 3) (-2 1 4)))
> (matrix-multiply '((1 2) (3 4)) '((-3 -8 3) (-2 1 4)))
Line 5,613: Line 5,613:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>const type: matrix is array array float;
<syntaxhighlight lang="seed7">const type: matrix is array array float;


const func matrix: (in matrix: left) * (in matrix: right) is func
const func matrix: (in matrix: left) * (in matrix: right) is func
Line 5,638: Line 5,638:
end for;
end for;
end if;
end if;
end func;</lang>
end func;</syntaxhighlight>


Original source: [http://seed7.sourceforge.net/algorith/math.htm#mmult]
Original source: [http://seed7.sourceforge.net/algorith/math.htm#mmult]
Line 5,649: Line 5,649:
The SequenceL definition mirrors that definition more or less exactly:
The SequenceL definition mirrors that definition more or less exactly:


<lang sequencel>matmul(A(2), B(2)) [i,j] :=
<syntaxhighlight lang="sequencel">matmul(A(2), B(2)) [i,j] :=
let k := 1...size(B);
let k := 1...size(B);
in sum( A[i,k] * B[k,j] );
in sum( A[i,k] * B[k,j] );
Line 5,660: Line 5,660:
[-2, 1, 4]];
[-2, 1, 4]];
test := matmul(a, b);</lang>
test := matmul(a, b);</syntaxhighlight>


It can be written a little more simply using the all keyword:
It can be written a little more simply using the all keyword:


<lang sequencel>matmul(A(2), B(2)) [i,j] := sum( A[i,all] * B[all,j] );</lang>
<syntaxhighlight lang="sequencel">matmul(A(2), B(2)) [i,j] := sum( A[i,all] * B[all,j] );</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func matrix_multi(a, b) {
<syntaxhighlight lang="ruby">func matrix_multi(a, b) {
var m = [[]]
var m = [[]]
for r in ^a {
for r in ^a {
Line 5,693: Line 5,693:
for line in matrix_multi(a, b) {
for line in matrix_multi(a, b) {
say line.map{|i|'%3d' % i }.join(', ')
say line.map{|i|'%3d' % i }.join(', ')
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 9, 12, 15
<pre> 9, 12, 15
Line 5,704: Line 5,704:
{{works with|OpenAxiom}}
{{works with|OpenAxiom}}
{{works with|Axiom}}
{{works with|Axiom}}
<lang SPAD>(1) -> A:=matrix [[1,2],[3,4],[5,6],[7,8]]
<syntaxhighlight lang="spad">(1) -> A:=matrix [[1,2],[3,4],[5,6],[7,8]]


+1 2+
+1 2+
Line 5,729: Line 5,729:
| |
| |
+39 54 69+
+39 54 69+
Type: Matrix(Integer)</lang>
Type: Matrix(Integer)</syntaxhighlight>


Domain:[http://fricas.github.io/api/Matrix.html?highlight=matrix Matrix(R)]
Domain:[http://fricas.github.io/api/Matrix.html?highlight=matrix Matrix(R)]


=={{header|SQL}}==
=={{header|SQL}}==
<lang sql>CREATE TABLE a (x integer, y integer, e real);
<syntaxhighlight lang="sql">CREATE TABLE a (x integer, y integer, e real);
CREATE TABLE b (x integer, y integer, e real);
CREATE TABLE b (x integer, y integer, e real);


Line 5,753: Line 5,753:
INTO TABLE c
INTO TABLE c
FROM a AS lhs, b AS rhs
FROM a AS lhs, b AS rhs
WHERE lhs.x = 0 AND rhs.y = 0;</lang>
WHERE lhs.x = 0 AND rhs.y = 0;</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>structure IMatrix = struct
<syntaxhighlight lang="sml">structure IMatrix = struct
fun dot(x,y) = Vector.foldli (fn (i,xi,agg) => agg+xi*Vector.sub(y,i)) 0 x
fun dot(x,y) = Vector.foldli (fn (i,xi,agg) => agg+xi*Vector.sub(y,i)) 0 x
fun x*y =
fun x*y =
Line 5,779: Line 5,779:
in
in
toList (m1*m2)
toList (m1*m2)
end;</lang>
end;</syntaxhighlight>
'''Output:'''
'''Output:'''
<lang sml>val it = [[~7,~6,11],[~17,~20,25]] : int list list</lang>
<syntaxhighlight lang="sml">val it = [[~7,~6,11],[~17,~20,25]] : int list list</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
=== Stata matrices ===
=== Stata matrices ===
<lang stata>. mat a=1,2,3\4,5,6
<syntaxhighlight lang="stata">. mat a=1,2,3\4,5,6
. mat b=1,1,0,0\1,0,0,1\0,0,1,1
. mat b=1,1,0,0\1,0,0,1\0,0,1,1
. mat c=a*b
. mat c=a*b
Line 5,793: Line 5,793:
c1 c2 c3 c4
c1 c2 c3 c4
r1 3 1 3 5
r1 3 1 3 5
r2 9 4 6 11</lang>
r2 9 4 6 11</syntaxhighlight>
=== Mata ===
=== Mata ===
<lang stata>: a=1,2,3\4,5,6
<syntaxhighlight lang="stata">: a=1,2,3\4,5,6
: b=1,1,0,0\1,0,0,1\0,0,1,1
: b=1,1,0,0\1,0,0,1\0,0,1,1
: a*b
: a*b
Line 5,802: Line 5,802:
1 | 3 1 3 5 |
1 | 3 1 3 5 |
2 | 9 4 6 11 |
2 | 9 4 6 11 |
+---------------------+</lang>
+---------------------+</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>@inlinable
<syntaxhighlight lang="swift">@inlinable
public func matrixMult<T: Numeric>(_ m1: [[T]], _ m2: [[T]]) -> [[T]] {
public func matrixMult<T: Numeric>(_ m1: [[T]], _ m2: [[T]]) -> [[T]] {
let n = m1[0].count
let n = m1[0].count
Line 5,864: Line 5,864:
let m3 = matrixMult(m1, m2)
let m3 = matrixMult(m1, m2)


printMatrix(m3)</lang>
printMatrix(m3)</syntaxhighlight>


{{out}}
{{out}}
Line 5,872: Line 5,872:


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang tailspin>
<syntaxhighlight lang="tailspin">
operator (A matmul B)
operator (A matmul B)
$A -> \[i](
$A -> \[i](
Line 5,907: Line 5,907:
' -> !OUT::write
' -> !OUT::write
($a matmul $b) -> printMatrix&{w:2} -> !OUT::write
($a matmul $b) -> printMatrix&{w:2} -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 5,926: Line 5,926:
=={{header|Tcl}}==
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
{{works with|Tcl|8.5}}
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5
namespace path ::tcl::mathop
namespace path ::tcl::mathop
proc matrix_multiply {a b} {
proc matrix_multiply {a b} {
Line 5,945: Line 5,945:
}
}
return $temp
return $temp
}</lang>
}</syntaxhighlight>
Using the <code>print_matrix</code> procedure defined in [[Matrix Transpose#Tcl]]
Using the <code>print_matrix</code> procedure defined in [[Matrix Transpose#Tcl]]
<pre>% print_matrix [matrix_multiply {{1 2} {3 4}} {{-3 -8 3} {-2 1 4}}]
<pre>% print_matrix [matrix_multiply {{1 2} {3 4}} {{-3 -8 3} {-2 1 4}}]
Line 5,953: Line 5,953:
=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Store your matrices in <tt>[A]</tt> and <tt>[B]</tt>.
Store your matrices in <tt>[A]</tt> and <tt>[B]</tt>.
<lang ti83b>Disp [A]*[B]</lang>
<syntaxhighlight lang="ti83b">Disp [A]*[B]</syntaxhighlight>
An error will show if the matrices have invalid dimensions for multiplication.
An error will show if the matrices have invalid dimensions for multiplication.
<br><br>'''Other way:''' enter directly your matrices:
<br><br>'''Other way:''' enter directly your matrices:
<lang ti83b>[[1,2][3,4][5,6][7,8]]*[[1,2,3][4,5,6]]</lang>
<syntaxhighlight lang="ti83b">[[1,2][3,4][5,6][7,8]]*[[1,2,3][4,5,6]]</syntaxhighlight>
{{out}}
{{out}}
[[9 12 15]
[[9 12 15]
Line 5,967: Line 5,967:
{{trans|Mathematica}}
{{trans|Mathematica}}


<lang ti89b>[1,2; 3,4; 5,6; 7,8] → m1
<syntaxhighlight lang="ti89b">[1,2; 3,4; 5,6; 7,8] → m1
[1,2,3; 4,5,6] → m2
[1,2,3; 4,5,6] → m2
m1 * m2</lang>
m1 * m2</syntaxhighlight>


Or without the variables:
Or without the variables:


<lang ti89b>[1,2; 3,4; 5,6; 7,8] * [1,2,3; 4,5,6]</lang>
<syntaxhighlight lang="ti89b">[1,2; 3,4; 5,6; 7,8] * [1,2,3; 4,5,6]</syntaxhighlight>


The result (without prettyprinting) is:
The result (without prettyprinting) is:


<lang ti89b>[[9,12,15][19,26,33][29,40,51][39,54,69]]</lang>
<syntaxhighlight lang="ti89b">[[9,12,15][19,26,33][29,40,51][39,54,69]]</syntaxhighlight>


=={{header|Transd}}==
=={{header|Transd}}==
<lang scheme>#lang transd
<syntaxhighlight lang="scheme">#lang transd




Line 5,996: Line 5,996:
(lout C))
(lout C))
)
)
}</lang>{{out}}
}</syntaxhighlight>{{out}}
<pre>
<pre>
[[50, 40, 30, 20, 10],
[[50, 40, 30, 20, 10],
Line 6,006: Line 6,006:


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang bash>
<syntaxhighlight lang="bash">
#!/bin/bash
#!/bin/bash


Line 6,190: Line 6,190:
echo
echo
echo
echo
</syntaxhighlight>
</lang>


=={{header|Ursala}}==
=={{header|Ursala}}==
Line 6,198: Line 6,198:
the built in rational number type.
the built in rational number type.


<lang Ursala>#import rat
<syntaxhighlight lang="ursala">#import rat


a =
a =
Line 6,220: Line 6,220:
#cast %qLL
#cast %qLL


test = mmult(a,b)</lang>
test = mmult(a,b)</syntaxhighlight>
{{out}}
{{out}}
<pre><
<pre><
Line 6,230: Line 6,230:
=={{header|VBA}}==
=={{header|VBA}}==
Using Excel. The resulting matrix should be smaller than 5461 elements.
Using Excel. The resulting matrix should be smaller than 5461 elements.
<lang vb>Function matrix_multiplication(a As Variant, b As Variant) As Variant
<syntaxhighlight lang="vb">Function matrix_multiplication(a As Variant, b As Variant) As Variant
matrix_multiplication = WorksheetFunction.MMult(a, b)
matrix_multiplication = WorksheetFunction.MMult(a, b)
End Function</lang>
End Function</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Dim matrix1(2,2)
Dim matrix1(2,2)
matrix1(0,0) = 3 : matrix1(0,1) = 7 : matrix1(0,2) = 4
matrix1(0,0) = 3 : matrix1(0,1) = 7 : matrix1(0,2) = 4
Line 6,255: Line 6,255:
Next
Next
End Sub
End Sub
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 6,265: Line 6,265:


=={{header|Visual FoxPro}}==
=={{header|Visual FoxPro}}==
<lang vfp>
<syntaxhighlight lang="vfp">
LOCAL ARRAY a[4,2], b[2,3], c[4,3]
LOCAL ARRAY a[4,2], b[2,3], c[4,3]
CLOSE DATABASES ALL
CLOSE DATABASES ALL
Line 6,308: Line 6,308:
ENDIF
ENDIF
ENDPROC
ENDPROC
</syntaxhighlight>
</lang>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-matrix}}
{{libheader|Wren-matrix}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/matrix" for Matrix
<syntaxhighlight lang="ecmascript">import "/matrix" for Matrix
import "/fmt" for Fmt
import "/fmt" for Fmt


Line 6,333: Line 6,333:
Fmt.mprint(b, 2, 0)
Fmt.mprint(b, 2, 0)
System.print("\nMatrix A x B:\n")
System.print("\nMatrix A x B:\n")
Fmt.mprint(a * b, 3, 0)</lang>
Fmt.mprint(a * b, 3, 0)</syntaxhighlight>


{{out}}
{{out}}
Line 6,358: Line 6,358:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>proc Mat4x1Mul(M, V); \Multiply matrix M times column vector V
<syntaxhighlight lang="xpl0">proc Mat4x1Mul(M, V); \Multiply matrix M times column vector V
real M, \4x4 matrix [M] * [V] -> [V]
real M, \4x4 matrix [M] * [V] -> [V]
V; \column vector
V; \column vector
Line 6,384: Line 6,384:
N(3,C):= W(3,C);
N(3,C):= W(3,C);
];
];
];</lang>
];</syntaxhighlight>


=={{header|XSLT 1.0}}==
=={{header|XSLT 1.0}}==
With input document ...
With input document ...


<lang xml><?xml-stylesheet href="matmul.templ.xsl" type="text/xsl"?>
<syntaxhighlight lang="xml"><?xml-stylesheet href="matmul.templ.xsl" type="text/xsl"?>
<mult>
<mult>
<A>
<A>
Line 6,401: Line 6,401:
<r><c>4</c><c>5</c><c>6</c></r>
<r><c>4</c><c>5</c><c>6</c></r>
</B>
</B>
</mult></lang>
</mult></syntaxhighlight>


... and this referenced stylesheet ...
... and this referenced stylesheet ...


<lang xml><xsl:stylesheet version="1.0"
<syntaxhighlight lang="xml"><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
>
Line 6,481: Line 6,481:
</xsl:template>
</xsl:template>


</xsl:stylesheet></lang>
</xsl:stylesheet></syntaxhighlight>
{{out}} (in a browser):
{{out}} (in a browser):
Line 6,499: Line 6,499:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang yabasic>dim a(4, 2)
<syntaxhighlight lang="yabasic">dim a(4, 2)
a(0, 0) = 1 : a(0, 1) = 2
a(0, 0) = 1 : a(0, 1) = 2
a(1, 0) = 3 : a(1, 1) = 4
a(1, 0) = 3 : a(1, 1) = 4
Line 6,527: Line 6,527:
print "invalid dimensions"
print "invalid dimensions"
end if
end if
end</lang>
end</syntaxhighlight>




=={{header|zkl}}==
=={{header|zkl}}==
Using the GNU Scientific Library:
Using the GNU Scientific Library:
<lang zkl>var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
<syntaxhighlight lang="zkl">var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
A:=GSL.Matrix(4,2).set(1,2, 3,4, 5,6, 7,8);
A:=GSL.Matrix(4,2).set(1,2, 3,4, 5,6, 7,8);
B:=GSL.Matrix(2,3).set(1,2,3, 4,5,6);
B:=GSL.Matrix(2,3).set(1,2,3, 4,5,6);
(A*B).format().println(); // creates a new matrix</lang>
(A*B).format().println(); // creates a new matrix</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,545: Line 6,545:
Or, using lists:
Or, using lists:
{{trans|BASIC}}
{{trans|BASIC}}
<lang zkl>fcn matMult(a,b){
<syntaxhighlight lang="zkl">fcn matMult(a,b){
n,m,p:=a[0].len(),a.len(),b[0].len();
n,m,p:=a[0].len(),a.len(),b[0].len();
ans:=(0).pump(m,List().write, (0).pump(p,List,0).copy); // matrix of zeros
ans:=(0).pump(m,List().write, (0).pump(p,List,0).copy); // matrix of zeros
foreach i,j,k in (m,p,n){ ans[i][j]+=a[i][k]*b[k][j]; }
foreach i,j,k in (m,p,n){ ans[i][j]+=a[i][k]*b[k][j]; }
ans
ans
}</lang>
}</syntaxhighlight>
<lang zkl>a:=L( L(1,2,), L(3,4,), L(5,6,), L(7,8) );
<syntaxhighlight lang="zkl">a:=L( L(1,2,), L(3,4,), L(5,6,), L(7,8) );
b:=L( L(1,2,3,), L(4,5,6) );
b:=L( L(1,2,3,), L(4,5,6) );
printM(matMult(a,b));
printM(matMult(a,b));


fcn printM(m){ m.pump(Console.println,rowFmt) }
fcn printM(m){ m.pump(Console.println,rowFmt) }
fcn rowFmt(row){ ("%4d "*row.len()).fmt(row.xplode()) }</lang>
fcn rowFmt(row){ ("%4d "*row.len()).fmt(row.xplode()) }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,566: Line 6,566:


=={{header|zonnon}}==
=={{header|zonnon}}==
<lang zonnon>
<syntaxhighlight lang="zonnon">
module MatrixOps;
module MatrixOps;
type
type
Line 6,596: Line 6,596:
Multiplication;
Multiplication;
end MatrixOps.
end MatrixOps.
</syntaxhighlight>
</lang>


=={{header|ZPL}}==
=={{header|ZPL}}==
<syntaxhighlight lang="zpl">
<lang ZPL>
program matmultSUMMA;
program matmultSUMMA;


Line 6,741: Line 6,741:
return retval;
return retval;
end;
end;
</syntaxhighlight>
</lang>