Matrix multiplication: Difference between revisions

m
 
(95 intermediate revisions by 40 users not shown)
Line 6:
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
<br><br>
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">F matrix_mul(m1, m2)
assert(m1[0].len == m2.len)
V r = [[0.0] * m2[0].len] * m1.len
L(j) 0 .< m1.len
L(i) 0 .< m2[0].len
V s = 0.0
L(k) 0 .< m2.len
s += m1[j][k] * m2[k][i]
r[j][i] = s
R r
 
F to_str(m)
V result = ‘([’
L(r) m
I result.len > 2
result ‘’= "]\n ["
L(val) r
result ‘’= ‘#5.2’.format(val)
R result‘])’
 
V a = [[1.0, 1.0, 1.0, 1.0],
[2.0, 4.0, 8.0, 16.0],
[3.0, 9.0, 27.0, 81.0],
[4.0, 16.0, 64.0, 256.0]]
 
V b = [[ 4.0, -3.0 , 4/3.0, -1/4.0],
[-13/3.0, 19/4.0, -7/3.0, 11/24.0],
[ 3/2.0, -2.0 , 7/6.0, -1/4.0],
[ -1/6.0, 1/4.0, -1/6.0, 1/24.0]]
 
print(to_str(a))
print(to_str(b))
print(to_str(matrix_mul(a, b)))
print(to_str(matrix_mul(b, a)))</syntaxhighlight>
 
{{out}}
<pre>
([ 1.00 1.00 1.00 1.00]
[ 2.00 4.00 8.00 16.00]
[ 3.00 9.00 27.00 81.00]
[ 4.00 16.00 64.00 256.00])
([ 4.00 -3.00 1.33 -0.25]
[ -4.33 4.75 -2.33 0.46]
[ 1.50 -2.00 1.17 -0.25]
[ -0.17 0.25 -0.17 0.04])
([ 1.00 0.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 0.00 1.00])
([ 1.00 0.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 -0.00 1.00])
</pre>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Matrix multiplication 06/08/2015
MATRIXRC CSECT Matrix multiplication
USING MATRIXRC,R13
Line 113 ⟶ 171:
W DS CL16
YREGS
END MATRIXRC</langsyntaxhighlight>
{{out}}
<pre> 9 12 15
Line 119 ⟶ 177:
29 40 51
39 54 69</pre>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
 
DEFINE PTR="CARD"
 
TYPE Matrix=[
BYTE width,height
PTR data] ;INT ARRAY
 
PROC PrintMatrix(Matrix POINTER m)
BYTE i,j
INT ARRAY d
CHAR ARRAY s(10)
 
d=m.data
FOR j=0 TO m.height-1
DO
FOR i=0 TO m.width-1
DO
StrI(d(j*m.width+i),s)
PrintF("%2S ",s)
OD
PutE()
OD
RETURN
 
PROC Create(MATRIX POINTER m BYTE w,h INT ARRAY a)
m.width=w
m.height=h
m.data=a
RETURN
 
PROC MatrixMul(Matrix POINTER m1,m2,res)
BYTE i,j,k
INT ARRAY d1,d2,dres,sum
 
IF m1.width#m2.height THEN
Print("Invalid size of matrices for multiplication!")
Break()
FI
d1=m1.data
d2=m2.data
dres=res.data
 
res.width=m2.width
res.height=m1.height
 
FOR j=0 TO res.height-1
DO
FOR i=0 TO res.width-1
DO
sum=0
FOR k=0 TO m1.width-1
DO
sum==+d1(k+j*m1.width)*d2(i+k*m2.width)
OD
dres(j*res.width+i)=sum
OD
OD
RETURN
 
PROC Main()
MATRIX m1,m2,res
INT ARRAY
d1=[2 1 4 0 1 1],
d2=[6 3 65535 0 1 1 0 4 65534 5 0 2],
dres(8)
 
Put(125) PutE() ;clear the screen
 
Create(m1,3,2,d1)
Create(m2,4,3,d2)
Create(res,0,0,dres)
MatrixMul(m1,m2,res)
 
PrintMatrix(m1)
PutE() PrintE("multiplied by") PutE()
PrintMatrix(m2)
PutE() PrintE("equals") PutE()
PrintMatrix(res)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Matrix_multiplication.png Screenshot from Atari 8-bit computer]
<pre>
2 1 4
0 1 1
 
multiplied by
 
6 3 -1 0
1 1 0 4
-2 5 0 2
 
equals
 
5 27 -2 12
-1 6 0 6
</pre>
 
=={{header|Ada}}==
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:
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
 
Line 153 ⟶ 311:
begin
Put (A * B);
end Matrix_Product;</langsyntaxhighlight>
{{out}}
<pre>
Line 162 ⟶ 320:
</pre>
The following code illustrates how matrix multiplication could be implemented from scratch:
<langsyntaxhighlight lang="ada">package Matrix_Ops is
type Matrix is array (Natural range <>, Natural range <>) of Float;
function "*" (Left, Right : Matrix) return Matrix;
Line 187 ⟶ 345:
return Temp;
end "*";
end Matrix_Ops;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 195 ⟶ 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}}
An example of user defined Vector and Matrix Multiplication Operators:
<langsyntaxhighlight lang="algol68">MODE FIELD = LONG REAL; # field type is LONG REAL #
INT default upb:=3;
MODE VECTOR = [default upb]FIELD;
Line 254 ⟶ 412:
exception index error:
putf(stand error, $x"Exception: index error."l$)
)</langsyntaxhighlight>
{{out}}
<pre>
Line 363 ⟶ 521:
exception index error:
putf(stand error, $x"Exception: index error."l$)
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
main:
first matrix=0, second matrix=0,a=-1
{5,2},rand array(a),mulby(10),ceil, cpy(first matrix), puts,{"\n"},puts
{2,3},rand array(a),mulby(10),ceil, cpy(second matrix), puts,{"\n"},puts
{first matrix,second matrix},mat mul, println
exit(0)
</syntaxhighlight>
Alternatively, the follow code in macro-natural-Hopper:
<syntaxhighlight lang="amazing hopper">
#include <natural.h>
#include <hopper.h>
main:
get a matrix of '5,2' integer random numbers, remember it in 'first matrix' and put it with a newline
get a matrix of '2,3' integer random numbers, remember it in 'second matrix' and put it with a newline
now take 'first matrix', and take 'second matrix', and multiply it; then, print with a new line.
exit(0)
</syntaxhighlight>
{{out}}
<pre>
2 2
1 5
3 4
6 6
4 8
 
7 1 6
6 2 4
 
26 6 20
37 11 26
45 11 34
78 18 60
76 20 56
</pre>
 
=={{header|APL}}==
Matrix multiply in APL is just <tt>+.×</tt>. For example:
 
<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)
B ← ⌹A ⍝ Matrix inverse of A
'F6.2' ⎕FMT A x B
1.00 0.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 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.
 
 
 
 
 
 
 
 
 
 
 
=={{header|AppleScript}}==
{{trans|JavaScript}}
<syntaxhighlight lang="applescript">--------------------- MATRIX MULTIPLY --------------------
<lang AppleScript>-- matrixMultiply :: Num a => [[a]] -> [[a]] -> [[a]]
 
-- matrixMultiply :: Num a => [[a]] -> [[a]] -> [[a]]
to matrixMultiply(a, b)
script rows
Line 386 ⟶ 610:
 
 
-- TEST ---------------------------------- TEST -------------------------
on run
matrixMultiply({¬
Line 403 ⟶ 627:
 
 
-- GENERIC FUNCTIONS --------------------------- GENERIC FUNCTIONS -------------------
 
-- dotProduct :: [n] -> [n] -> Maybe n
Line 419 ⟶ 643:
end if
end dotProduct
 
 
-- foldr :: (a -> b -> a) -> a -> [b] -> a
Line 431 ⟶ 656:
end tell
end foldr
 
 
-- map :: (a -> b) -> [a] -> [b]
Line 443 ⟶ 669:
end tell
end map
 
 
-- min :: Ord a => a -> a -> a
Line 452 ⟶ 679:
end if
end min
 
 
-- Lift 2nd class handler function into 1st class script wrapper
Line 464 ⟶ 692:
end if
end mReturn
 
 
-- product :: Num a => [a] -> a
Line 475 ⟶ 704:
foldr(mult, 1, xs)
end product
 
 
-- sum :: Num a => [a] -> a
Line 486 ⟶ 716:
foldr(add, 0, xs)
end sum
 
 
-- transpose :: [[a]] -> [[a]]
Line 503 ⟶ 734:
map(column, item 1 of xss)
end transpose
 
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
Line 514 ⟶ 746:
return lst
end tell
end zipWith</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{{51, -8, 26, -18}, {-8, -38, -6, 34}, {33, 42, 38, -14}, {17, 74, 72, 44}}</langsyntaxhighlight>
 
=={{header|APLArturo}}==
Matrix multiply in APL is just <tt>+.×</tt>. For example:
 
<syntaxhighlight lang="rebol">printMatrix: function [m][
<lang apl> x ← +.×
loop m 'row -> print map row 'val [pad to :string .format:".2f" val 6]
print "--------------------------------"
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)
]
B ← ⌹A ⍝ Matrix inverse of A
'F6.2' ⎕FMT A x B
1.00 0.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 0.00 1.00</lang>
 
multiply: function [a,b][
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.
X: size a
Y: size first b
result: array.of: @[X Y] 0
 
loop 0..X-1 'i [
loop 0..Y-1 'j [
loop 0..(size first a)-1 'k ->
result\[i]\[j]: result\[i]\[j] + a\[i]\[k] * b\[k]\[j]
]
]
return result
]
A: [[1.0 1.0 1.0 1.0]
[2.0 4.0 8.0 16.0]
[3.0 9.0 27.0 81.0]
[4.0 16.0 64.0 256.0]]
 
B: @[@[ 4.0 0-3.0 4/3.0 0-1/4.0]
@[0-13/3.0 19/4.0 0-7/3.0 11/24.0]
@[ 3/2.0 0-2.0 7/6.0 0-1/4.0]
@[ 0-1/6.0 1/4.0 0-1/6.0 1/24.0]]
 
printMatrix A
printMatrix B
printMatrix multiply A B
printMatrix multiply B A</syntaxhighlight>
 
{{out}}
 
<pre> 1.00 1.00 1.00 1.00
2.00 4.00 8.00 16.00
3.00 9.00 27.00 81.00
4.00 16.00 64.00 256.00
--------------------------------
4.00 -3.00 1.33 -0.25
-4.33 4.75 -2.33 0.46
1.50 -2.00 1.17 -0.25
-0.17 0.25 -0.17 0.04
--------------------------------
1.00 0.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 0.00 1.00
--------------------------------
1.00 0.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 -0.00 1.00
--------------------------------</pre>
 
=={{header|AutoHotkey}}==
ahk [http://www.autohotkey.com/forum/topic44657-150.html discussion]
<langsyntaxhighlight lang="autohotkey">Matrix("b"," ; rows separated by ","
, 1 2 ; entries separated by space or tab
, 2 3
Line 587 ⟶ 862:
}
}
}</langsyntaxhighlight>
===Using Objects===
<langsyntaxhighlight AutoHotkeylang="autohotkey">Multiply_Matrix(A,B){
if (A[1].MaxIndexCount() <> B.MaxIndexCount())
return ["Dimension Error"]
RColsR := A[1].MaxIndex()>B[1].MaxIndex()?, RRows := A[1].MaxIndexCount(), RCols:B= b[1].MaxIndexCount()
RRows := A.MaxIndex()>B.MaxIndex()?A.MaxIndex():B.MaxIndex(), R := []
Loop, % RRows {
RRow:=A_Index
loop, % RCols {
RCol:=A_Index, v := 0
loop % A[1].MaxIndexCount()
col := A_Index, v += A[RRow, col] * B[col, RCol]
R[RRow,RCol] := v
}
}
return R
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">A := [[1,2]
, [3,4]
, [5,6]
Line 623 ⟶ 897:
Res .= (A_Index=1?"":"`t") col (Mod(A_Index,M[1].MaxIndex())?"":"`n")
return Trim(Res,"`n")
}</langsyntaxhighlight>
{{out}}
<pre>9 12 15
Line 631 ⟶ 905:
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk"># Usage: GAWK -f MATRIX_MULTIPLICATION.AWK filename
# Separate matrices a and b by a blank line
BEGIN {
Line 684 ⟶ 958:
function max(m, n) {
return m > n ? m : n
}</langsyntaxhighlight>
<p><b>Input:</b></p>
<pre>
Line 703 ⟶ 977:
{{works with|QuickBasic|4.5}}
{{trans|Java}}
<langsyntaxhighlight lang="qbasic">Assume the matrices to be multiplied are a and b
IF (LEN(a,2) = LEN(b)) 'if valid dims
n = LEN(a,2)
Line 726 ⟶ 1,000:
ELSE
PRINT "invalid dimensions"
END IF</langsyntaxhighlight>
 
==={{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]].
<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)
3 FOR I = 1 TO O: FOR J = 1 TO P: IF K THEN READ B(I,J)
4 IF NOT K THEN READ A(I,J)
5 NEXT J,I,K: DIM AB(M,P): FOR I = 1 TO M: FOR J = 1 TO P: FOR K = 1 TO N:AB(I,J) = AB(I,J) + (A(I,K) * B(K,J)): NEXT K,J,I: FOR I = 1 TO M: FOR J = 1 TO P: PRINT MID$ (S$,1 + (J = 1),1)AB(I,J);:S$ = " " + CHR$ (13): NEXT J,I
10000 DATA4,2
10010 DATA1,2,3,4,5,6,7,8
20000 DATA2,3
20010 DATA1,2,3,4,5,6</syntaxhighlight>
 
===Full BASIC===
{{works with|Full BASIC}}
{{trans|BBC_BASIC}}
<langsyntaxhighlight lang="basic">DIM matrix1(4,2),matrix2(2,3)
 
MAT READ matrix1
Line 744 ⟶ 1,030:
 
MAT product=matrix1*matrix2
MAT PRINT product</langsyntaxhighlight>
{{out}}
<pre> 9 12 15
Line 755 ⟶ 1,041:
(assumes default lower bound of 0):
 
<langsyntaxhighlight lang="bbcbasic"> DIM matrix1(3,1), matrix2(1,2), product(3,2)
matrix1() = 1, 2, \
Line 773 ⟶ 1,059:
PRINT
NEXT
</syntaxhighlight>
</lang>
{{out}}
<pre> 9 12 15
Line 780 ⟶ 1,066:
39 54 69</pre>
 
=={{header|BQN}}==
<code>Mul</code> is a matrix multiplication idiom from [https://mlochbaum.github.io/bqncrate/ BQNcrate.]
 
<syntaxhighlight lang="bqn">Mul ← +˝∘×⎉1‿∞
 
(>⟨
⟨1, 2, 3⟩
⟨4, 5, 6⟩
⟨7, 8, 9⟩
⟩) Mul >⟨
⟨1, 2, 3, 4⟩
⟨5, 6, 7, 8⟩
⟨9, 10, 11, 12⟩
⟩</syntaxhighlight><syntaxhighlight lang="bqn">┌─
╵ 20 23 26 29
56 68 80 92
92 113 134 155
┘</syntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=TXVsIOKGkCAry53iiJjDl+KOiTHigL/iiJ4KCig+4p+oCiAg4p+oMSwgMiwgM+KfqQogIOKfqDQsIDUsIDbin6kKICDin6g3LCA4LCA54p+pCuKfqSkgTXVsID7in6gKICDin6gxLCAgMiwgIDMsIDTin6kKICDin6g1LCAgNiwgIDcsIDjin6kKICDin6g5LCAxMCwgMTEsIDEy4p+pCuKfqQo= Try It!]
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) {{1 2}{3 4}{5 6}{7 8}}{{1 2 3}{4 5 6}}mmsp
9 12 15
Line 789 ⟶ 1,094:
29 40 51
39 54 69
</syntaxhighlight>
</lang>
 
=={{header|C}}==
<syntaxhighlight lang="c">#include <stdio.h>
For performance critical work involving matrices, especially large or sparse ones, always consider using an established library such as BLAS first.
<lang c>#include <stdio.h>
#include <stdlib.h>
 
#define MAT_ELEM(rows,cols,r,c) (r*cols+c)
/* Make the data structure self-contained. Element at row i and col j
is x[i * w + j]. More often than not, though, you might want
to represent a matrix some other way */
typedef struct { int h, w; double *x;} matrix_t, *matrix;
 
//Improve performance by assuming output matrices do not overlap with
inline double dot(double *a, double *b, int len, int step)
//input matrices. If this is C++, use the __restrict extension instead
#ifdef __cplusplus
typedef double * const __restrict MAT_OUT_t;
#else
typedef double * const restrict MAT_OUT_t;
#endif
typedef const double * const MAT_IN_t;
 
static inline void mat_mult(
const int m,
const int n,
const int p,
MAT_IN_t a,
MAT_IN_t b,
MAT_OUT_t c)
{
for (int row=0; row<m; row++) {
double r = 0;
for (int col=0; col<p; col++) {
while (len--) {
c[MAT_ELEM(m,p,row,col)] = 0;
r += *a++ * *b;
for (int i=0; i<n; i++) {
b += step;
c[MAT_ELEM(m,p,row,col)] += a[MAT_ELEM(m,n,row,i)]*b[MAT_ELEM(n,p,i,col)];
}
}
return r;
}
}
}
 
static inline void mat_show(
matrix mat_new(int h, int w)
const int m,
const int p,
MAT_IN_t a)
{
for (int row=0; row<m;row++) {
matrix r = malloc(sizeof(matrix_t) + sizeof(double) * w * h);
for (int col=0; col<p;col++) {
r->h = h, r->w = w;
printf("\t%7.3f", a[MAT_ELEM(m,p,row,col)]);
r->x = (double*)(r + 1);
}
return r;
putchar('\n');
}
}
 
int main(void)
matrix mat_mul(matrix a, matrix b)
{
double a[4*4] = {1, 1, 1, 1,
matrix r;
2, 4, 8, 16,
double *p, *pa;
3, 9, 27, 81,
int i, j;
4, 16, 64, 256};
if (a->w != b->h) return 0;
 
double b[4*3] = { 4.0, -3.0, 4.0/3,
r = mat_new(a->h, b->w);
-13.0/3, 19.0/4, -7.0/3,
p = r->x;
for (pa = a->x, i = 0; i < a->h; i++ 3.0/2, pa += a->w)2.0, 7.0/6,
-1.0/6, 1.0/4, -1.0/6};
for (j = 0; j < b->w; j++)
*p++ = dot(pa, b->x + j, a->w, b->w);
return r;
}
 
double c[4*3] = {0};
void mat_show(matrix a)
{
mat_mult(4,4,3,a,b,c);
int i, j;
mat_show(4,3,c);
double *p = a->x;
return 0;
for (i = 0; i < a->h; i++, putchar('\n'))
for (j = 0; j < a->w; j++)
printf("\t%7.3f", *p++);
putchar('\n');
}
 
</syntaxhighlight>
int main()
{
double da[] = { 1, 1, 1, 1,
2, 4, 8, 16,
3, 9, 27, 81,
4,16, 64, 256 };
double db[] = { 4.0, -3.0, 4.0/3,
-13.0/3, 19.0/4, -7.0/3,
3.0/2, -2.0, 7.0/6,
-1.0/6, 1.0/4, -1.0/6};
 
matrix_t a = { 4, 4, da }, b = { 4, 3, db };
matrix c = mat_mul(&a, &b);
 
/* mat_show(&a), mat_show(&b); */
mat_show(c);
/* free(c) */
return 0;
}</lang>
 
=={{header|C sharp|C#}}==
Line 868 ⟶ 1,166:
This code should work with any version of the .NET Framework and C# language
 
==={{header|Class}}===
<lang csharp>public class Matrix
 
<syntaxhighlight lang="csharp">public class Matrix
{
int n;
Line 911 ⟶ 1,211:
return result;
}
}</langsyntaxhighlight>
 
==={{header|Extension Method}}===
Implementation of matrix multiplication and matrix display for 2D arrays using an extension method
 
<syntaxhighlight lang="csharp">
public static class LinearAlgebra
{
public static double[,] Product(this double[,] a, double[,] b)
{
int na = a.GetLength(0), ma = a.GetLength(1);
int nb = b.GetLength(0), mb = b.GetLength(1);
 
if (ma != nb)
{
throw new ArgumentException("Incompatible Matrix Sizes.", nameof(b));
}
double[,] c = new double[na, mb];
for (int i = 0; i < na; i++)
{
for (int j = 0; j < mb; j++)
{
double sum = 0;
for (int k = 0; k < ma; k++)
{
sum += a[i, k] * b[k, j];
}
c[i, j] = sum;
}
}
return c;
}
public static string Show(this double[,] a, string formatting = "g4", int columnWidth = 12)
{
int na = a.GetLength(0), ma = a.GetLength(1);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < na; i++)
{
sb.Append("|");
for (int j = 0; j < ma; j++)
{
sb.Append(" ");
if (columnWidth > 0)
{
sb.Append(a[i, j].ToString(formatting).PadLeft(columnWidth));
}
else if (columnWidth < 0)
{
sb.Append(a[i, j].ToString(formatting).PadRight(columnWidth));
}
else
{
throw new ArgumentOutOfRangeException(nameof(columnWidth), "Must be non-negative");
}
}
sb.AppendLine(" |");
}
return sb.ToString();
}
}
class Program
{
static void Main(string[] args)
{
double[,] A = new double[,] { { 1, 2, 3 }, { 4, 5, 6 } };
double[,] B = new double[,] { { 8, 7, 6 }, { 5, 4, 3 }, { 2, 1, 0 } };
 
double[,] C = A.Product(B);
Console.WriteLine("A=");
Console.WriteLine(A.Show("f4", 8));
Console.WriteLine("B=");
Console.WriteLine(B.Show("f4", 8));
Console.WriteLine("C=A*B");
Console.WriteLine(C.Show("f4", 8));
 
}
}
</syntaxhighlight>
 
{{out}}
<pre>
A=
| 1.0000 2.0000 3.0000 |
| 4.0000 5.0000 6.0000 |
 
B=
| 8.0000 7.0000 6.0000 |
| 5.0000 4.0000 3.0000 |
| 2.0000 1.0000 0.0000 |
 
C=A*B
| 24.0000 18.0000 12.0000 |
| 69.0000 54.0000 39.0000 |
</pre>
 
=={{header|C++}}==
Line 918 ⟶ 1,311:
 
{{libheader|Blitz++}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <blitz/tinymat.h>
 
Line 938 ⟶ 1,331:
 
std::cout << C << std::endl;
}</langsyntaxhighlight>
{{out}}
(3,3):
Line 947 ⟶ 1,340:
===Generic solution===
main.cpp
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include "matrix.h"
Line 984 ⟶ 1,377:
 
} /* main() */
</syntaxhighlight>
</lang>
 
matrix.h
<langsyntaxhighlight lang="cpp">
#ifndef _MATRIX_H
#define _MATRIX_H
Line 1,165 ⟶ 1,558:
 
#endif /* _MATRIX_H */
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,174 ⟶ 1,567:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">alias Matrix => Integer[][];
 
void printMatrix(Matrix m) {
Line 1,238 ⟶ 1,631:
print("something went wrong!");
}
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 3]
Line 1,251 ⟶ 1,644:
[ 58, 64]
[139, 154]</pre>
 
=={{header|Chapel}}==
 
Overload the '*' operator for arrays
<syntaxhighlight lang="chapel">proc *(a:[], b:[]) {
 
if (a.eltType != b.eltType) then
writeln("type mismatch: ", a.eltType, " ", b.eltType);
 
var ad = a.domain.dims();
var bd = b.domain.dims();
var (arows, acols) = ad;
var (brows, bcols) = bd;
if (arows != bcols) then
writeln("dimension mismatch: ", ad, " ", bd);
 
var c:[{arows, bcols}] a.eltType = 0;
 
for i in arows do
for j in bcols do
for k in acols do
c(i,j) += a(i,k) * b(k,j);
 
return c;
}</syntaxhighlight>
 
example usage (I could not figure out the syntax for multi-dimensional array literals)
<syntaxhighlight lang="chapel">var m1:[{1..2, 1..2}] int;
m1(1,1) = 1; m1(1,2) = 2;
m1(2,1) = 3; m1(2,2) = 4;
writeln(m1);
 
var m2:[{1..2, 1..2}] int;
m2(1,1) = 2; m2(1,2) = 3;
m2(2,1) = 4; m2(2,2) = 5;
writeln(m2);
 
var m3 = m1 * m2;
writeln(m3);
 
var m4:[{1..2, 1..3}] int;
m4(1, 1) = 1; m4(1, 2) = 2; m4(1, 3) = 3;
m4(2, 1) = 4; m4(2, 2) = 5; m4(2, 3) = 6;
writeln(m4);
 
var m5:[{1..3, 1..2}] int;
m5(1, 1) = 6; m5(1, 2) = -1;
m5(2, 1) = 3; m5(2, 2) = 2;
m5(3, 1) = 0; m5(3, 2) = -3;
writeln(m5);
 
writeln(m4 * m5);</syntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">
(defn transpose
[s]
Line 1,271 ⟶ 1,716:
 
(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]])</langsyntaxhighlight>
 
{{out}}
Line 1,280 ⟶ 1,725:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun matrix-multiply (a b)
(flet ((col (mat i) (mapcar #'(lambda (row) (elt row i)) mat))
(row (mat i) (elt mat i)))
Line 1,288 ⟶ 1,733:
 
;; example use:
(matrix-multiply '((1 2) (3 4)) '((-3 -8 3) (-2 1 4)))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">(defun matrix-multiply (matrix1 matrix2)
(mapcar
(lambda (row)
(apply #'mapcar
(lambda (&rest column)
(apply #'+ (mapcar #'* row column))) matrix2)) matrix1))</langsyntaxhighlight>
 
The following version uses 2D arrays as inputs.
 
<langsyntaxhighlight lang="lisp">(defun mmul (A B)
(let* ((m (car (array-dimensions A)))
(n (cadr (array-dimensions A)))
Line 1,310 ⟶ 1,755:
sum (* (aref A i j)
(aref B j k))))))
C))</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="lisp">(mmul #2a((1 2) (3 4)) #2a((-3 -8 3) (-2 1 4)))
#2A((-7 -6 11) (-17 -20 25))
</syntaxhighlight>
</lang>
 
Another version:
 
<langsyntaxhighlight lang="lisp">(defun mmult (a b)
(loop
with m = (array-dimension a 0)
Line 1,332 ⟶ 1,777:
sum (* (aref a i j)
(aref b j k)))))
finally (return c)))</langsyntaxhighlight>
 
=={{header|Chapel}}==
 
Overload the '*' operator for arrays
<lang chapel>proc *(a:[], b:[]) {
 
if (a.eltType != b.eltType) then
writeln("type mismatch: ", a.eltType, " ", b.eltType);
 
var ad = a.domain.dims();
var bd = b.domain.dims();
var (arows, acols) = ad;
var (brows, bcols) = bd;
if (arows != bcols) then
writeln("dimension mismatch: ", ad, " ", bd);
 
var c:[{arows, bcols}] a.eltType = 0;
 
for i in arows do
for j in bcols do
for k in acols do
c(i,j) += a(i,k) * b(k,j);
 
return c;
}</lang>
 
example usage (I could not figure out the syntax for multi-dimensional array literals)
<lang chapel>var m1:[{1..2, 1..2}] int;
m1(1,1) = 1; m1(1,2) = 2;
m1(2,1) = 3; m1(2,2) = 4;
writeln(m1);
 
var m2:[{1..2, 1..2}] int;
m2(1,1) = 2; m2(1,2) = 3;
m2(2,1) = 4; m2(2,2) = 5;
writeln(m2);
 
var m3 = m1 * m2;
writeln(m3);
 
var m4:[{1..2, 1..3}] int;
m4(1, 1) = 1; m4(1, 2) = 2; m4(1, 3) = 3;
m4(2, 1) = 4; m4(2, 2) = 5; m4(2, 3) = 6;
writeln(m4);
 
var m5:[{1..3, 1..2}] int;
m5(1, 1) = 6; m5(1, 2) = -1;
m5(2, 1) = 3; m5(2, 2) = 2;
m5(3, 1) = 0; m5(3, 2) = -3;
writeln(m5);
 
writeln(m4 * m5);</lang>
 
=={{header|D}}==
===Basic Version===
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.conv, std.numeric,
std.array, std.algorithm;
 
Line 1,421 ⟶ 1,814:
writefln("B = \n" ~ form ~ "\n", b);
writefln("A * B = \n" ~ form, matrixMul(a, b));
}</langsyntaxhighlight>
{{out}}
<pre>A =
Line 1,438 ⟶ 1,831:
 
===Short Version===
<langsyntaxhighlight 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*/ {
Line 1,453 ⟶ 1,846:
writefln("B = \n" ~ form ~ "\n", b);
writefln("A * B = \n" ~ form, matMul(a, b));
}</langsyntaxhighlight>
The output is the same.
 
===Pure Short Version===
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.numeric, std.algorithm;
 
T[][] matMul(T)(immutable T[][] A, immutable T[][] B) pure nothrow {
Line 1,473 ⟶ 1,866:
writefln("B = \n" ~ form ~ "\n", b);
writefln("A * B = \n" ~ form, matMul(a, b));
}</langsyntaxhighlight>
The output is the same.
 
Line 1,479 ⟶ 1,872:
All array sizes are verified at compile-time (and no matrix is copied).
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.numeric, std.algorithm, std.traits;
 
alias TMMul_helper(M1, M2) = Unqual!(ForeachType!(ForeachType!M1))
Line 1,511 ⟶ 1,904:
matrixMul(a, b, result);
writefln("A * B = \n" ~ form, result);
}</langsyntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
<syntaxhighlight lang="delphi">
program Matrix_multiplication;
 
{$APPTYPE CONSOLE}
=={{header|Ela}}==
 
uses
<lang ela>open list
System.SysUtils;
 
type
mmult a b = [ [ sum $ zipWith (*) ar bc \\ bc <- (transpose b) ] \\ ar <- a ]
TMatrix = record
values: array of array of Double;
Rows, Cols: Integer;
constructor Create(Rows, Cols: Integer);
class operator Multiply(a: TMatrix; b: TMatrix): TMatrix;
function ToString: string;
end;
 
{ TMatrix }
[[1, 2],
[3, 4]] `mmult` [[-3, -8, 3],
[-2, 1, 4]]</lang>
 
constructor TMatrix.Create(Rows, Cols: Integer);
=={{header|ELLA}}==
var
Sample originally from ftp://ftp.dra.hmg.gb/pub/ella (a now dead link) - Public release.
i: Integer;
begin
Self.Rows := Rows;
self.Cols := Cols;
SetLength(values, Rows);
for i := 0 to High(values) do
SetLength(values[i], Cols);
end;
 
class operator TMatrix.Multiply(a, b: TMatrix): TMatrix;
Code for matrix multiplication hardware design verification:
var
<lang ella>MAC ZIP = ([INT n]TYPE t: vector1 vector2) -> [n][2]t:
rows, cols, l: Integer;
[INT k = 1..n](vector1[k], vector2[k]).
i, j: Integer;
sum: Double;
MAC TRANSPOSE = ([INT n][INT m]TYPE t: matrix) -> [m][n]t:
k: Integer;
[INT i = 1..m] [INT j = 1..n] matrix[j][i].
begin
rows := a.Rows;
cols := b.Cols;
l := a.Cols;
if l <> b.Rows then
raise Exception.Create('Illegal matrix dimensions for multiplication');
result := TMatrix.create(a.rows, b.Cols);
for i := 0 to rows - 1 do
for j := 0 to cols - 1 do
begin
sum := 0.0;
for k := 0 to l - 1 do
sum := sum + (a.values[i, k] * b.values[k, j]);
result.values[i, j] := sum;
end;
end;
 
function TMatrix.ToString: string;
MAC INNER_PRODUCT{FN * = [2]TYPE t -> TYPE s, FN + = [2]s -> s}
var
= ([INT n][2]t: vector) -> s:
i, j: Integer;
IF n = 1 THEN *vector[1]
begin
ELSE *vector[1] + INNER_PRODUCT {*,+} vector[2..n]
Result := '[';
FI.
for i := 0 to 2 do
begin
if i > 0 then
Result := Result + #10;
Result := Result + '[';
for j := 0 to 2 do
begin
if j > 0 then
Result := Result + ', ';
Result := Result + format('%5.2f', [values[i, j]]);
end;
Result := Result + ']';
end;
Result := Result + ']';
end;
 
var
MAC MATRIX_MULT {FN * = [2]TYPE t->TYPE s, FN + = [2]s->s} =
a, b, r: TMatrix;
([INT n][INT m]t: matrix1, [m][INT p]t: matrix2) -> [n][p]s:
i, j: Integer;
BEGIN
LET transposed_matrix2 = TRANSPOSE matrix2.
OUTPUT [INT i = 1..n][INT j = 1..p]
INNER_PRODUCT{*,+}ZIP(matrix1[i],transposed_matrix2[j])
END.
 
begin
a := TMatrix.Create(3, 3);
b := TMatrix.Create(3, 3);
a.values := [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
b.values := [[2, 2, 2], [5, 5, 5], [7, 7, 7]];
r := a * b;
 
Writeln('a: ');
TYPE element = NEW elt/(1..20),
Writeln(a.ToString, #10);
product = NEW prd/(1..1200).
Writeln('b: ');
Writeln(b.ToString, #10);
Writeln('a * b:');
Writeln(r.ToString);
readln;
 
end.</syntaxhighlight>
FN PLUS = (product: integer1 integer2) -> product:
{{out}}
ARITH integer1 + integer2.
<pre>a:
[[ 1,00, 2,00, 3,00]
[ 4,00, 5,00, 6,00]
[ 7,00, 8,00, 9,00]]
 
b:
FN MULT = (element: integer1 integer2) -> product:
[[ 2,00, 2,00, 2,00]
ARITH integer1 * integer2.
[ 5,00, 5,00, 5,00]
[ 7,00, 7,00, 7,00]]
 
a * b:
FN MULT_234 = ([2][3]element:matrix1, [3][4]element:matrix2) ->
[[33,00, 33,00, 33,00]
[2][4]product:
[75,00, 75,00, 75,00]
MATRIX_MULT{MULT,PLUS}(matrix1, matrix2).
[117,00, 117,00, 117,00]]</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
func[][] matmul m1[][] m2[][] .
for i to len m1[][]
r[][] &= [ ]
for j = 1 to len m2[1][]
r[i][] &= 0
for k to len m2[][]
r[i][j] += m1[i][k] * m2[k][j]
.
.
.
return r[][]
.
a[][] = [ [ 1 2 3 ] [ 4 5 6 ] ]
b[][] = [ [ 1 2 ] [ 3 4 ] [ 5 6 ] ]
print matmul a[][] b[][]
</syntaxhighlight>
 
{{out}}
FN TEST = () -> [2][4]product:
<pre>
( LET m1 = ((elt/2, elt/1, elt/1),
[
(elt/3, elt/6, elt/9)),
[ 22 28 ]
m2 = ((elt/6, elt/1, elt/3, elt/4),
[ 49 64 ]
(elt/9, elt/2, elt/8, elt/3),
]
(elt/6, elt/4, elt/1, elt/2)).
</pre>
OUTPUT
MULT_234 (m1, m2)
).
 
COM test: just displaysignal MOC</lang>
 
=={{header|Euphoria}}==
<lang euphoria>function matrix_mul(sequence a, sequence b)
sequence c
if length(a[1]) != length(b) then
return 0
else
c = repeat(repeat(0,length(b[1])),length(a))
for i = 1 to length(a) do
for j = 1 to length(b[1]) do
for k = 1 to length(a[1]) do
c[i][j] += a[i][k]*b[k][j]
end for
end for
end for
return c
end if
end function</lang>
 
=={{header|EGL}}==
<syntaxhighlight lang="egl">
<lang EGL>
program Matrix_multiplication type BasicProgram {}
Line 1,627 ⟶ 2,079:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
 
<syntaxhighlight lang="ela">open list
 
mmult a b = [ [ sum $ zipWith (*) ar bc \\ bc <- (transpose b) ] \\ ar <- a ]
 
[[1, 2],
[3, 4]] `mmult` [[-3, -8, 3],
[-2, 1, 4]]</syntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">
def mult(m1, m2) do
Enum.map m1, fn (x) -> Enum.map t(m2), fn (y) -> Enum.zip(x, y)
Line 1,644 ⟶ 2,106:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">
(defvar M1 '((2 1 4)
(0 1 1)))
 
(defvar M2 '(( 6 3 -1 0)
( 1 1 0 4)
(-2 5 0 2)))
 
(seq-map (lambda (a1)
(seq-map (lambda (a2) (apply #'+ (seq-mapn #'* a1 a2)))
(apply #'seq-mapn #'list M2)))
M1)
</syntaxhighlight>
 
{{out}}
<pre>
((5 27 -2 12) (-1 6 0 6))
</pre>
 
=={{header|ELLA}}==
Sample originally from ftp://ftp.dra.hmg.gb/pub/ella (a now dead link) - Public release.
 
Code for matrix multiplication hardware design verification:
<syntaxhighlight lang="ella">MAC ZIP = ([INT n]TYPE t: vector1 vector2) -> [n][2]t:
[INT k = 1..n](vector1[k], vector2[k]).
MAC TRANSPOSE = ([INT n][INT m]TYPE t: matrix) -> [m][n]t:
[INT i = 1..m] [INT j = 1..n] matrix[j][i].
 
MAC INNER_PRODUCT{FN * = [2]TYPE t -> TYPE s, FN + = [2]s -> s}
= ([INT n][2]t: vector) -> s:
IF n = 1 THEN *vector[1]
ELSE *vector[1] + INNER_PRODUCT {*,+} vector[2..n]
FI.
 
MAC MATRIX_MULT {FN * = [2]TYPE t->TYPE s, FN + = [2]s->s} =
([INT n][INT m]t: matrix1, [m][INT p]t: matrix2) -> [n][p]s:
BEGIN
LET transposed_matrix2 = TRANSPOSE matrix2.
OUTPUT [INT i = 1..n][INT j = 1..p]
INNER_PRODUCT{*,+}ZIP(matrix1[i],transposed_matrix2[j])
END.
 
 
TYPE element = NEW elt/(1..20),
product = NEW prd/(1..1200).
 
FN PLUS = (product: integer1 integer2) -> product:
ARITH integer1 + integer2.
 
FN MULT = (element: integer1 integer2) -> product:
ARITH integer1 * integer2.
 
FN MULT_234 = ([2][3]element:matrix1, [3][4]element:matrix2) ->
[2][4]product:
MATRIX_MULT{MULT,PLUS}(matrix1, matrix2).
 
FN TEST = () -> [2][4]product:
( LET m1 = ((elt/2, elt/1, elt/1),
(elt/3, elt/6, elt/9)),
m2 = ((elt/6, elt/1, elt/3, elt/4),
(elt/9, elt/2, elt/8, elt/3),
(elt/6, elt/4, elt/1, elt/2)).
OUTPUT
MULT_234 (m1, m2)
).
 
COM test: just displaysignal MOC</syntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
 
%% Multiplies two matrices. Usage example:
Line 1,706 ⟶ 2,238:
multiply_row_by_col(Row, []) ->
[].
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,712 ⟶ 2,244:
[[7,16],[22,40]]
</pre>
 
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM MAT_PROD
 
Line 1,753 ⟶ 2,284:
 
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}<pre>
9 12 15
Line 1,761 ⟶ 2,292:
</pre>
 
=={{header|F#Euphoria}}==
<syntaxhighlight lang="euphoria">function matrix_mul(sequence a, sequence b)
<lang F#>
sequence c
if length(a[1]) != length(b) then
return 0
else
c = repeat(repeat(0,length(b[1])),length(a))
for i = 1 to length(a) do
for j = 1 to length(b[1]) do
for k = 1 to length(a[1]) do
c[i][j] += a[i][k]*b[k][j]
end for
end for
end for
return c
end if
end function</syntaxhighlight>
 
=={{header|Excel}}==
Excel's MMULT function yields the matrix product of two arrays.
 
The formula in cell B2 here populates the '''B2:D3''' grid:
{{Out}}
{| class="wikitable"
|-
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx
! colspan="8" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=MMULT(F2#, F6#)
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;"
|
| A
| B
| C
| D
| E
| F
| G
| H
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1
|
| colspan="3" style="font-weight:bold" | Matrix product
|
| colspan="3" style="font-weight:bold" | M1
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2
|
| style="text-align:right; background-color:#cbcefb" | -7
| style="text-align:right" | -6
| style="text-align:right" | 11
|
| style="text-align:right" | 1
| style="text-align:right" | 2
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 3
|
| style="text-align:right" | -17
| style="text-align:right" | -20
| style="text-align:right" | 25
|
| style="text-align:right" | 3
| style="text-align:right" | 4
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 4
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 5
|
|
|
|
|
| colspan="3" style="font-weight:bold" | M2
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 6
|
|
|
|
|
| style="text-align:right" | -3
| style="text-align:right" | -8
| style="text-align:right" | 3
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 7
|
|
|
|
|
| style="text-align:right" | -2
| style="text-align:right" | 1
| style="text-align:right" | 4
|}
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
let MatrixMultiply (matrix1 : _[,] , matrix2 : _[,]) =
let result_row = (matrix1.GetLength 0)
Line 1,775 ⟶ 2,409:
ret
 
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
Line 1,788 ⟶ 2,422:
Using a list of lists representation. The multiplication is done using three nested loops.
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,820 ⟶ 2,454:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,827 ⟶ 2,461:
</pre>
 
=={{header|Fermat}}==
<syntaxhighlight lang="fermat">
Array a[3,2]
Array b[2,3]
[a]:=[(2,3,5,7,11,13)]
[b]:=[(1,1,2,3,5,8)]
[a]*[b]
</syntaxhighlight>
{{out}}
<pre>
[[ 9, 25, 66, `
14, 39, 103, `
18, 49, 129 ]]
</pre>
 
=={{header|Forth}}==
{{libheader|Forth Scientific Library}}
{{works with|gforth|0.7.9_20170308}}
<langsyntaxhighlight lang="forth">S" fsl-util.fs" REQUIRED
S" fsl/dynmem.seq" REQUIRED
: F+! ( addr -- ) ( F: r -- ) DUP F@ F+ F! ;
Line 1,844 ⟶ 2,492:
A{{ 3 3 B{{ 3 3 & C{{ mat*
3 3 C{{ }}fprint</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight 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(size(a,1), size(b,2)) :: c ! C is an array whose first dimension (row) size
Line 1,872 ⟶ 2,520:
do i = 1, n
print *, c(i,:)
end do</langsyntaxhighlight>
For Intel 14.x or later (with compiler switch -assume realloc_lhs)
<langsyntaxhighlight lang="fortran">
program mm
real , allocatable :: a(:,:),b(:,:)
Line 1,882 ⟶ 2,530:
print'(<n>f15.7)',transpose(matmul(a,b))
end program
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">type Matrix
dim as double m( any , any )
declare constructor ( )
declare constructor ( byval x as uinteger , byval y as uinteger )
end type
 
constructor Matrix ( )
end constructor
 
constructor Matrix ( byval x as uinteger , byval y as uinteger )
redim this.m( x - 1 , y - 1 )
end constructor
 
operator * ( byref a as Matrix , byref b as Matrix ) as Matrix
dim as Matrix ret
dim as uinteger i, j, k
if ubound( a.m , 2 ) = ubound( b.m , 1 ) and ubound( a.m , 1 ) = ubound( b.m , 2 ) then
redim ret.m( ubound( a.m , 1 ) , ubound( b.m , 2 ) )
for i = 0 to ubound( a.m , 1 )
for j = 0 to ubound( b.m , 2 )
for k = 0 to ubound( b.m , 1 )
ret.m( i , j ) += a.m( i , k ) * b.m( k , j )
next k
next j
next i
end if
return ret
end operator
 
'some garbage matrices for demonstration
dim as Matrix a = Matrix(4 , 2)
a.m(0 , 0) = 1 : a.m(0 , 1) = 0
a.m(1 , 0) = 0 : a.m(1 , 1) = 1
a.m(2 , 0) = 2 : a.m(2 , 1) = 3
a.m(3 , 0) = 0.75 : a.m(3 , 1) = -0.5
dim as Matrix b = Matrix( 2 , 4 )
b.m(0 , 0) = 3.1 : b.m(0 , 1) = 1.6 : b.m(0 , 2) = -99 : b.m (0, 3) = -8
b.m(1 , 0) = 2.7 : b.m(1 , 1) = 0.6 : b.m(1 , 2) = 0 : b.m(1,3) = 21
dim as Matrix c = a * b
print c.m(0, 0), c.m(0, 1), c.m(0, 2), c.m(0, 3)
print c.m(1, 0), c.m(1, 1), c.m(1, 2), c.m(1, 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)
</syntaxhighlight>
 
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">matprod[a is array, b is array] :=
{
c = makeArray[[length[a], length[b@0]], 0]
Line 1,899 ⟶ 2,594:
 
return c
}</langsyntaxhighlight>
 
=={{header|Futhark}}==
Line 1,906 ⟶ 2,601:
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 =
map (fn xr => map (fn yc => reduce (+) 0 (zipWith (*) xr yc))
(transpose y))
x
</syntaxhighlight>
</lang>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Built-in
A := [[1, 2], [3, 4], [5, 6], [7, 8]];
B := [[1, 2, 3], [4, 5, 6]];
Line 1,932 ⟶ 2,627:
# [ 19, 26, 33 ],
# [ 29, 40, 51 ],
# [ 39, 54, 69 ] ]</langsyntaxhighlight>
 
 
=={{header|Generic}}==
<syntaxhighlight lang="cpp">
generic coordinaat
{
ecs
uuii
 
coordinaat() { ecs=+a uuii=+a}
 
coordinaat(ecs_set uuii_set) { ecs = ecs_set uuii=uuii_set }
 
operaator<(c)
{
iph ecs < c.ecs return troo
iph c.ecs < ecs return phals
iph uuii < c.uuii return troo
return phals
}
 
operaator==(connpair) // eecuuols and not eecuuols deriiu phronn operaator<
{
iph this < connpair return phals
iph connpair < this return phals
return troo
}
 
operaator!=(connpair)
{
iph this < connpair return troo
iph connpair < this return troo
return phals
}
 
too_string()
{
return "(" + ecs.too_string() + "," + uuii.too_string() + ")"
}
 
print()
{
str = too_string()
str.print()
}
 
println()
{
str = too_string()
str.println()
}
}
 
generic nnaatrics
{
s // this is a set of coordinaat/ualioo pairs.
iteraator // this field holds an iteraator phor the nnaatrics.
 
nnaatrics() // no parameters required phor nnaatrics construction.
{
s = nioo set() // create a nioo set of coordinaat/ualioo pairs.
iteraator = nul // the iteraator is initially set to nul.
}
 
nnaatrics(copee) // copee the nnaatrics.
{
s = nioo set() // create a nioo set of coordinaat/ualioo pairs.
iteraator = nul // the iteraator is initially set to nul.
 
r = copee.rouus
c = copee.cols
i = 0
uuiil i < r
{
j = 0
uuiil j < c
{
this[i j] = copee[i j]
j++
}
i++
}
}
 
begin { get { return s.begin } } // property: used to commence manual iteraashon.
 
end { get { return s.end } } // property: used to dephiin the end itenn of iteraashon
 
operaator<(a) // les than operaator is corld bii the avl tree algorithnns
{ // this operaator innpliis phor instance that you could potenshalee hav sets ou nnaatricss.
iph cees < a.cees // connpair the cee sets phurst.
return troo
els iph a.cees < cees
return phals
els // the cee sets are eecuuol thairphor connpair nnaatrics elennents.
{
phurst1 = begin
lahst1 = end
phurst2 = a.begin
lahst2 = a.end
 
uuiil phurst1 != lahst1 && phurst2 != lahst2
{
iph phurst1.daata.ualioo < phurst2.daata.ualioo
return troo
els
{
iph phurst2.daata.ualioo < phurst1.daata.ualioo
return phals
els
{
phurst1 = phurst1.necst
phurst2 = phurst2.necst
}
}
}
 
return phals
}
}
 
operaator==(connpair) // eecuuols and not eecuuols deriiu phronn operaator<
{
iph this < connpair return phals
iph connpair < this return phals
return troo
}
 
operaator!=(connpair)
{
iph this < connpair return troo
iph connpair < this return troo
return phals
}
 
 
operaator[cee_a cee_b] // this is the nnaatrics indexer.
{
set
{
trii { s >> nioo cee_ualioo(new coordinaat(cee_a cee_b)) } catch {}
s << nioo cee_ualioo(new coordinaat(nioo integer(cee_a) nioo integer(cee_b)) ualioo)
}
get
{
d = s.get(nioo cee_ualioo(new coordinaat(cee_a cee_b)))
return d.ualioo
}
}
 
operaator>>(coordinaat) // this operaator reennoous an elennent phronn the nnaatrics.
{
s >> nioo cee_ualioo(coordinaat)
return this
}
 
iteraat() // and this is how to iterate on the nnaatrics.
{
iph iteraator.nul()
{
iteraator = s.lepht_nnohst
iph iteraator == s.heder
return nioo iteraator(phals nioo nun())
els
return nioo iteraator(troo iteraator.daata.ualioo)
}
els
{
iteraator = iteraator.necst
iph iteraator == s.heder
{
iteraator = nul
return nioo iteraator(phals nioo nun())
}
els
return nioo iteraator(troo iteraator.daata.ualioo)
}
}
 
couunt // this property returns a couunt ou elennents in the nnaatrics.
{
get
{
return s.couunt
}
}
 
ennptee // is the nnaatrics ennptee?
{
get
{
return s.ennptee
}
}
 
 
lahst // returns the ualioo of the lahst elennent in the nnaatrics.
{
get
{
iph ennptee
throuu "ennptee nnaatrics"
els
return s.lahst.ualioo
}
}
 
too_string() // conuerts the nnaatrics too aa string
{
return s.too_string()
}
 
print() // prints the nnaatrics to the consohl.
{
out = too_string()
out.print()
}
 
println() // prints the nnaatrics as a liin too the consohl.
{
out = too_string()
out.println()
}
 
cees // return the set ou cees ou the nnaatrics (a set of coordinaats).
{
get
{
k = nioo set()
phor e : s k << e.cee
return k
}
}
 
operaator+(p)
{
ouut = nioo nnaatrics()
phurst1 = begin
lahst1 = end
phurst2 = p.begin
lahst2 = p.end
uuiil phurst1 != lahst1 && phurst2 != lahst2
{
ouut[phurst1.daata.cee.ecs phurst1.daata.cee.uuii] = phurst1.daata.ualioo + phurst2.daata.ualioo
phurst1 = phurst1.necst
phurst2 = phurst2.necst
}
return ouut
}
operaator-(p)
{
ouut = nioo nnaatrics()
phurst1 = begin
lahst1 = end
phurst2 = p.begin
lahst2 = p.end
uuiil phurst1 != lahst1 && phurst2 != lahst2
{
ouut[phurst1.daata.cee.ecs phurst1.daata.cee.uuii] = phurst1.daata.ualioo - phurst2.daata.ualioo
phurst1 = phurst1.necst
phurst2 = phurst2.necst
}
return ouut
}
 
rouus
{
get
{
r = +a
phurst1 = begin
lahst1 = end
uuiil phurst1 != lahst1
{
iph r < phurst1.daata.cee.ecs r = phurst1.daata.cee.ecs
phurst1 = phurst1.necst
}
return r + +b
}
}
 
cols
{
get
{
c = +a
phurst1 = begin
lahst1 = end
uuiil phurst1 != lahst1
{
iph c < phurst1.daata.cee.uuii c = phurst1.daata.cee.uuii
phurst1 = phurst1.necst
}
return c + +b
}
}
 
operaator*(o)
{
iph cols != o.rouus throw "rouus-cols nnisnnatch"
reesult = nioo nnaatrics()
rouu_couunt = rouus
colunn_couunt = o.cols
loop = cols
i = +a
uuiil i < rouu_couunt
{
g = +a
uuiil g < colunn_couunt
{
sunn = +a.a
h = +a
uuiil h < loop
{
a = this[i h]
 
b = o[h g]
nn = a * b
sunn = sunn + nn
h++
}
 
reesult[i g] = sunn
 
g++
}
i++
}
return reesult
}
 
suuop_rouus(a b)
{
c = cols
i = 0
uuiil u < cols
{
suuop = this[a i]
this[a i] = this[b i]
this[b i] = suuop
i++
}
}
 
suuop_colunns(a b)
{
r = rouus
i = 0
uuiil i < rouus
{
suuopp = this[i a]
this[i a] = this[i b]
this[i b] = suuop
i++
}
}
 
transpohs
{
get
{
reesult = new nnaatrics()
 
r = rouus
c = cols
i=0
uuiil i < r
{
g = 0
uuiil g < c
{
reesult[g i] = this[i g]
g++
}
i++
}
 
return reesult
}
}
 
deternninant
{
get
{
rouu_couunt = rouus
colunn_count = cols
 
if rouu_couunt != colunn_count
throw "not a scuuair nnaatrics"
 
if rouu_couunt == 0
throw "the nnaatrics is ennptee"
 
if rouu_couunt == 1
return this[0 0]
 
if rouu_couunt == 2
return this[0 0] * this[1 1] -
this[0 1] * this[1 0]
 
temp = nioo nnaatrics()
 
det = 0.0
parity = 1.0
 
j = 0
uuiil j < rouu_couunt
{
k = 0
uuiil k < rouu_couunt-1
{
skip_col = phals
 
l = 0
uuiil l < rouu_couunt-1
{
if l == j skip_col = troo
 
if skip_col
n = l + 1
els
n = l
 
temp[k l] = this[k + 1 n]
l++
}
k++
}
 
det = det + parity * this[0 j] * temp.deeternninant
 
parity = 0.0 - parity
j++
}
 
return det
}
}
 
ad_rouu(a b)
{
c = cols
i = 0
uuiil i < c
{
this[a i] = this[a i] + this[b i]
i++
}
}
 
ad_colunn(a b)
{
c = rouus
i = 0
uuiil i < c
{
this[i a] = this[i a] + this[i b]
i++
}
}
 
subtract_rouu(a b)
{
c = cols
i = 0
uuiil i < c
{
this[a i] = this[a i] - this[b i]
i++
}
}
 
subtract_colunn(a b)
{
c = rouus
i = 0
uuiil i < c
{
this[i a] = this[i a] - this[i b]
i++
}
}
 
nnultiplii_rouu(rouu scalar)
{
c = cols
i = 0
uuiil i < c
{
this[rouu i] = this[rouu i] * scalar
i++
}
}
 
nnultiplii_colunn(colunn scalar)
{
r = rouus
i = 0
uuiil i < r
{
this[i colunn] = this[i colunn] * scalar
i++
}
}
 
diuiid_rouu(rouu scalar)
{
c = cols
i = 0
uuiil i < c
{
this[rouu i] = this[rouu i] / scalar
i++
}
}
 
diuiid_colunn(colunn scalar)
{
r = rouus
i = 0
uuiil i < r
{
this[i colunn] = this[i colunn] / scalar
i++
}
}
 
connbiin_rouus_ad(a b phactor)
{
c = cols
i = 0
uuiil i < c
{
this[a i] = this[a i] + phactor * this[b i]
i++
}
}
 
connbiin_rouus_subtract(a b phactor)
{
c = cols
i = 0
uuiil i < c
{
this[a i] = this[a i] - phactor * this[b i]
i++
}
}
 
connbiin_colunns_ad(a b phactor)
{
r = rouus
i = 0
uuiil i < r
{
this[i a] = this[i a] + phactor * this[i b]
i++
}
}
 
connbiin_colunns_subtract(a b phactor)
{
r = rouus
i = 0
uuiil i < r
{
this[i a] = this[i a] - phactor * this[i b]
i++
}
}
 
inuers
{
get
{
rouu_couunt = rouus
colunn_couunt = cols
 
iph rouu_couunt != colunn_couunt
throw "nnatrics not scuuair"
 
els iph rouu_couunt == 0
throw "ennptee nnatrics"
 
els iph rouu_couunt == 1
{
r = nioo nnaatrics()
r[0 0] = 1.0 / this[0 0]
return r
}
 
gauss = nioo nnaatrics(this)
 
i = 0
uuiil i < rouu_couunt
{
j = 0
uuiil j < rouu_couunt
{
iph i == j
 
gauss[i j + rouu_couunt] = 1.0
els
gauss[i j + rouu_couunt] = 0.0
j++
}
 
i++
}
 
j = 0
uuiil j < rouu_couunt
{
iph gauss[j j] == 0.0
{
k = j + 1
 
uuiil k < rouu_couunt
{
if gauss[k j] != 0.0 {gauss.nnaat.suuop_rouus(j k) break }
k++
}
 
if k == rouu_couunt throw "nnatrics is singioolar"
}
 
phactor = gauss[j j]
iph phactor != 1.0 gauss.diuiid_rouu(j phactor)
 
i = j+1
uuiil i < rouu_couunt
{
gauss.connbiin_rouus_subtract(i j gauss[i j])
i++
}
 
j++
}
 
i = rouu_couunt - 1
uuiil i > 0
{
k = i - 1
uuiil k >= 0
{
gauss.connbiin_rouus_subtract(k i gauss[k i])
k--
}
i--
}
 
reesult = nioo nnaatrics()
 
i = 0
uuiil i < rouu_couunt
{
j = 0
uuiil j < rouu_couunt
{
reesult[i j] = gauss[i j + rouu_couunt]
j++
}
i++
}
 
return reesult
}
}
 
}
</syntaxhighlight>
 
=={{header|Go}}==
===Library gonum/mat===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,958 ⟶ 3,327:
m.Mul(a, b)
fmt.Println(mat.Formatted(&m))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,966 ⟶ 3,335:
 
===Library go.matrix===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,993 ⟶ 3,362:
}
fmt.Printf("Product of A and B:\n%v\n", p)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,010 ⟶ 3,379:
 
===2D representation===
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,069 ⟶ 3,438:
fmt.Printf("Matrix B:\n%s\n\n", B)
fmt.Printf("Product of A and B:\n%s\n\n", P)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,087 ⟶ 3,456:
</pre>
===Flat representation===
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,142 ⟶ 3,511:
}
p.print("Product of A and B:")
}</langsyntaxhighlight>
Output is similar to 2D version.
 
Line 2,148 ⟶ 3,517:
=== 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.
<langsyntaxhighlight lang="groovy">def assertConformable = { a, b ->
assert a instanceof List
assert b instanceof List
Line 2,164 ⟶ 3,533:
}
}
}</langsyntaxhighlight>
 
=== 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.
<langsyntaxhighlight lang="groovy">def matmulWOT = { a, b ->
assertConformable(a, b)
Line 2,176 ⟶ 3,545:
}
}
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def m4by2 = [ [ 1, 2 ],
[ 3, 4 ],
[ 5, 6 ],
Line 2,189 ⟶ 3,558:
matmulWOIL(m4by2, m2by3).each { println it }
println()
matmulWOT(m4by2, m2by3).each { println it }</langsyntaxhighlight>
 
{{out}}
Line 2,206 ⟶ 3,575:
A somewhat inefficient version with lists (''transpose'' is expensive):
 
<langsyntaxhighlight Haskelllang="haskell">import Data.List
 
mmult :: Num a => [[a]] -> [[a]] -> [[a]]
Line 2,214 ⟶ 3,583:
test = [[1, 2],
[3, 4]] `mmult` [[-3, -8, 3],
[-2, 1, 4]]</langsyntaxhighlight>
===With Array===
A more efficient version, based on arrays:
 
<langsyntaxhighlight Haskelllang="haskell">import Data.Array
mmult :: (Ix i, Num a) => Array (i,i) a -> Array (i,i) a -> Array (i,i) a
Line 2,230 ⟶ 3,599:
jr = range (y1,y1')
kr = range (x1,x1')
l = [((i,j), sum [x!(i,k) * y!(k,j) | k <- kr]) | i <- ir, j <- jr]</langsyntaxhighlight>
===With List and without transpose===
<syntaxhighlight lang="haskell">multiply :: Num a => [[a]] -> [[a]] -> [[a]]
<lang Haskell>
multiply us vs = map (mult [] vs) us
foldlZipWith::(a -> b -> c) -> (d -> c -> d) -> d -> [a] -> [b] -> d
where
foldlZipWith _ _ u [] _ = u
foldlZipWith _ _ u _mult xs [] _ = uxs
mult xs _ [] = xs
foldlZipWith f g u (x:xs) (y:ys) = foldlZipWith f g (g u (f x y)) xs ys
mult [] (zs : zss) (y : ys) = mult (map (y *) zs) zss ys
mult xs (zs : zss) (y : ys) =
mult
(zipWith (\u v -> u + v * y) xs zs)
zss
ys
 
main :: IO ()
foldl1ZipWith::(a -> b -> c) -> (c -> c -> c) -> [a] -> [b] -> c
main =
foldl1ZipWith _ _ [] _ = error "First list is empty"
mapM_ print $
foldl1ZipWith _ _ _ [] = error "Second list is empty"
multiply
foldl1ZipWith f g (x:xs) (y:ys) = foldlZipWith f g (f x y) xs ys
[[1, 2], [3, 4]]
[[-3, -8, 3], [-2, 1, 4]]</syntaxhighlight>
{{out}}
<pre>[-7,-6,11]
[-17,-20,25]</pre>
 
===With List and without transpose - shorter===
multAdd::(a -> b -> c) -> (c -> c -> c) -> [[a]] -> [[b]] -> [[c]]
<syntaxhighlight lang="haskell">mult :: Num a => [[a]] -> [[a]] -> [[a]]
multAdd f g xs ys = map (\us -> foldl1ZipWith (\u vs -> map (f u) vs) (zipWith g) us ys) xs
mult uss vss =
let go xs
| null xs = []
| otherwise = foldl1 (zipWith (+)) xs
in go . zipWith (flip (map . (*))) vss <$> uss
 
main :: IO ()
mult:: Num a => [[a]] -> [[a]] -> [[a]]
main =
mult xs ys = multAdd (*) (+) xs ys
mapM_ print $
mult [[1, 2], [3, 4]] [[-3, -8, 3], [-2, 1, 4]]</syntaxhighlight>
{{out}}
<pre>[-7,-6,11]
[-17,-20,25]</pre>
 
===With Numeric.LinearAlgebra===
test a b = do
<syntaxhighlight lang="haskell">import Numeric.LinearAlgebra
let c = mult a b
putStrLn "a ="
mapM_ print a
putStrLn "b ="
mapM_ print b
putStrLn "c = a * b = mult a b ="
mapM_ print c
 
a, b :: Matrix I
main = test [[1, 2],[3, 4]] [[-3, -8, 3],[-2, 1, 4]]
a = (2 >< 2) [1, 2, 3, 4]
</lang>
 
b = (2 >< 3) [-3, -8, 3, -2, 1, 4]
 
main :: IO ()
main = print $ a <> b</syntaxhighlight>
{{out}}
<pre>
(2><3)
a =
[ -7, -6, 11
[1,2]
, -17, -20, 25 ]</pre>
[3,4]
b =
[-3,-8,3]
[-2,1,4]
c = a * b = mult a b =
[-7,-6,11]
[-17,-20,25]
</pre>
 
=={{header|HicEst}}==
<langsyntaxhighlight 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
Line 2,288 ⟶ 3,670:
ENDDO
 
DLG(DefWidth=4, Text=a, Text=b,Y=0, Text=res,Y=0)</langsyntaxhighlight>
<langsyntaxhighlight lang="hicest">a b res
1 2 1 2 3 9 12 15
3 4 4 5 6 19 26 33
5 6 29 40 51
7 8 39 54 69 </langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 2,299 ⟶ 3,681:
Using the provided matrix library:
 
<langsyntaxhighlight lang="icon">
link matrix
 
Line 2,313 ⟶ 3,695:
write_matrix ("", m3)
end
</syntaxhighlight>
</lang>
 
And a hand-crafted multiply procedure:
 
<langsyntaxhighlight lang="icon">
procedure multiply_matrix (m1, m2)
result := [] # to hold the final matrix
Line 2,333 ⟶ 3,715:
return result
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,351 ⟶ 3,733:
=={{header|IDL}}==
 
<langsyntaxhighlight lang="idl">result = arr1 # arr2</langsyntaxhighlight>
 
=={{header|Idris}}==
<langsyntaxhighlight lang="idris">import Data.Vect
 
Matrix : Nat -> Nat -> Type -> Type
Line 2,367 ⟶ 3,749:
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' [] _ = []</langsyntaxhighlight>
 
=={{header|J}}==
Matrix multiply in J is <code>+/ .*</code>. For example:
<langsyntaxhighlight 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)
Line 2,380 ⟶ 3,762:
0.00 1.00 0.00 0.00
0.00 0.00 1.00 0.00
0.00 0.00 0.00 1.00</langsyntaxhighlight>
The notation is for a generalized inner product so that
<langsyntaxhighlight 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. number of places where a value in row x equals the corresponding value in y</langsyntaxhighlight>
[[Floyd-Warshall_algorithm#J|etc.]]
 
Line 2,394 ⟶ 3,776:
 
=={{header|Java}}==
<langsyntaxhighlight 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[0].length != b.length) return null; //invalid dims
Line 2,412 ⟶ 3,794:
}
return ans;
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 2,420 ⟶ 3,802:
 
Extends [[Matrix Transpose#JavaScript]]
<langsyntaxhighlight lang="javascript">// returns a new matrix
Matrix.prototype.mult = function(other) {
if (this.width != other.height) {
Line 2,442 ⟶ 3,824:
var a = new Matrix([[1,2],[3,4]])
var b = new Matrix([[-3,-8,3],[-2,1,4]]);
print(a.mult(b));</langsyntaxhighlight>
{{out}}
<pre>-7,-6,11
Line 2,448 ⟶ 3,830:
 
====Functional====
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 2,514 ⟶ 3,896:
}
 
})();</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight Javascriptlang="javascript">[[51, -8, 26, -18], [-8, -38, -6, 34],
[33, 42, 38, -14], [17, 74, 72, 44]]</langsyntaxhighlight>
 
===ES6===
<langsyntaxhighlight JavaScriptlang="javascript">((() => {
'"use strict'";
 
// -------------- MATRIX MULTIPLICATION --------------
 
// matrixMultiply :: Num a => [[a]] -> [[a]] -> [[a]]
const matrixMultiply = (a, b) => {
const bColsb => transpose(b);{
return a.map(aRow => bCols.map(bCol const cols => dotProducttranspose(aRow, bCol))b);
}
 
// dotProduct :: Num a => [[a]] -> [[a]] ->return [[a]].map(
compose(
const dotProduct = (xs, ys) => sum(zipWith(product, xs, ys));
f => cols.map(f),
dotProduct
)
);
};
 
 
// ---------------------- TEST -----------------------
// GENERIC
const main = () =>
JSON.stringify(matrixMultiply(
[
[-1, 1, 4],
[6, -4, 2],
[-3, 5, 0],
[3, 7, -2]
]
)([
[-1, 1, 4, 8],
[6, 9, 10, 2],
[11, -4, 5, -3]
]));
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = (f, xs, ys) =>
xs.length === ys.length ? (
xs.map((x, i) => f(x, ys[i]))
) : undefined;
 
// --------------------- GENERIC ---------------------
// transpose :: [[a]] -> [[a]]
 
const transpose = xs =>
// compose (<<<) :: xs[0].map((_,b iCol-> c) =-> xs.map(rowa =-> row[iCol]b)); -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
 
 
// dotProduct :: Num a => [[a]] -> [[a]] -> [[a]]
const dotProduct = xs =>
// Sum of the products of the corresponding
// values in two lists of the same length.
compose(sum, zipWith(mul)(xs));
 
 
// mul :: Num a => a -> a -> a
const mul = a =>
b => a * b;
 
 
// sum :: (Num a) => [a] -> a
Line 2,549 ⟶ 3,965:
xs.reduce((a, x) => a + x, 0);
 
// product :: Num a => a -> a -> a
const product = (a, b) => a * b;
 
// transpose :: [[a]] -> [[a]]
const transpose = rows =>
// The columns of the input transposed
// into new rows.
// Simpler version of transpose, assuming input
// rows of even length.
Boolean(rows.length) ? rows[0].map(
(_, i) => rows.flatMap(
v => v[i]
)
) : [];
 
// TEST
return matrixMultiply(
[
[-1, 1, 4],
[6, -4, 2],
[-3, 5, 0],
[3, 7, -2]
],
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
[
const zipWith = f =>
[-1, 1, 4, 8],
// A list constructed [6,by 9,zipping 10,with 2],a
// custom function, rather [11,than -4, 5,with -3]the
]// default tuple constructor.
xs => ys => xs.map(
);
(x, i) => f(x)(ys[i])
).slice(
0, Math.min(xs.length, ys.length)
);
 
// --> [[51,MAIN -8, 26, -18], [-8, -38, -6, 34],
return main();
// [33, 42, 38, -14], [17, 74, 72, 44]]
}))();</langsyntaxhighlight>
{{Out}}
<lang JavaScriptpre>[[51, -8, 26, -18], [-8, -38, -6, 34], [33,42,38,-14],[17,74,72,44]]</pre>
[33, 42, 38, -14], [17, 74, 72, 44]]</lang>
 
=={{header|jq}}==
Line 2,580 ⟶ 4,000:
 
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.
<langsyntaxhighlight lang="jq">def dot_product(a; b):
a as $a | b as $b
| reduce range(0;$a|length) as $i (0; . + ($a[$i] * $b[$i]) );
Line 2,597 ⟶ 4,017:
| reduce range(0; $A|length) as $i
([]; reduce range(0; $p) as $j
(.; .[$i][$j] = dot_product( $A[$i]; $BT[$j] ) )) ;</langsyntaxhighlight>
'''Example'''
((2|sqrt)/2) as $r | [ [$r, $r], [(-($r)), $r]] as $R
Line 2,609 ⟶ 4,029:
Uses module listed in [[Matrix Transpose#Jsish]]
 
<langsyntaxhighlight lang="javascript">/* Matrix multiplication, in Jsish */
require('Matrix');
 
Line 2,626 ⟶ 4,046:
a.mult(b) ==> { height:2, mtx:[ [ -7, -6, 11 ], [ -17, -20, 25 ] ], width:3 }
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 2,634 ⟶ 4,054:
=={{header|Julia}}==
The multiplication is denoted by *
<langsyntaxhighlight Julialang="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}:
22 28
Line 2,642 ⟶ 4,062:
1-element Array{Int64,1}:
14
</syntaxhighlight>
</lang>
 
=={{header|K}}==
<langsyntaxhighlight lang="k"> (1 2;3 4)_mul (5 6;7 8)
(19 22
43 50)</langsyntaxhighlight>
 
=={{header|Klong}}==
<langsyntaxhighlight lang="k"> mul::{[a b];b::+y;{a::x;+/'{a*x}'b}'x}
[[1 2] [3 4]] mul [[5 6] [7 8]]
[[19 22]
[43 50]]</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
typealias Vector = DoubleArray
Line 2,695 ⟶ 4,115:
)
printMatrix(m1 * m2)
}</langsyntaxhighlight>
 
{{out}}
Line 2,704 ⟶ 4,124:
[17.0, 74.0, 72.0, 44.0]
</pre>
 
=={{header|Lambdatalk}}==
 
<syntaxhighlight lang="scheme">
{require lib_matrix}
 
1) applying a matrix to a vector
 
{def M
{M.new [[1,2,3],
[4,5,6],
[7,8,-9]]}}
-> M
 
{def V {M.new [1,2,3]} }
-> V
 
{M.multiply {M} {V}}
-> [14,32,-4]
 
2) matrix multiplication
 
{M.multiply {M} {M}}
-> [[ 30, 36,-12],
[ 66, 81,-12],
[-24,-18,150]]
</syntaxhighlight>
 
=={{header|Lang5}}==
<langsyntaxhighlight Lang5lang="lang5">[[1 2 3] [4 5 6]] 'm dress
[[1 2] [3 4] [5 6]] 'm dress * .</langsyntaxhighlight>
{{out}}
<pre>[
Line 2,718 ⟶ 4,165:
Use the LFE <code>transpose/1</code> function from [[Matrix transposition]].
 
<langsyntaxhighlight lang="lisp">
(defun matrix* (matrix-1 matrix-2)
(list-comp
Line 2,726 ⟶ 4,173:
(lists:foldl #'+/2 0
(lists:zipwith #'*/2 a b)))))
</syntaxhighlight>
</lang>
 
Usage example in the LFE REPL:
 
<langsyntaxhighlight lang="lisp">
> (set ma '((1 2)
(3 4)
Line 2,740 ⟶ 4,187:
> (matrix* ma mb)
((5 11 17 23) (11 25 39 53) (17 39 61 83) (23 53 83 113))
</syntaxhighlight>
</lang>
 
=={{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.
<syntaxhighlight lang="lb">
<lang lb>
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"
Line 2,755 ⟶ 4,202:
MatrixP$ =MatrixMultiply$( MatrixA$, MatrixB$)
call DisplayMatrix MatrixP$
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,777 ⟶ 4,224:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">TO LISTVMD :A :F :C :NV
;PROCEDURE LISTVMD
;A = LIST
Line 2,881 ⟶ 4,328:
THIS_IS: 5 ROWS X 5 COLS
{{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}}</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function MatMul( m1, m2 )
if #m1[1] ~= #m2 then -- inner matrix-dimensions must agree
return nil
Line 2,914 ⟶ 4,361:
end
io.write("\n")
end </langsyntaxhighlight>
 
===SciLua===
Using the sci.alg library from scilua.org
<langsyntaxhighlight Lualang="lua">local alg = require("sci.alg")
mat1 = alg.tomat{{1, 2, 3}, {4, 5, 6}}
mat2 = alg.tomat{{1, 2}, {3, 4}, {5, 6}}
mat3 = mat1[] ** mat2[]
print(mat3)</langsyntaxhighlight>
{{out}}
<pre>+22.00000,+28.00000
+49.00000,+64.00000</pre>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckMatMult {
\\ Matrix Multiplication
Line 2,995 ⟶ 4,443:
}
CheckMatMult2
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,004 ⟶ 4,452:
0 0 0 1
</pre>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">A := <<1|2|3>,<4|5|6>>;
 
B := <<1,2,3>|<4,5,6>|<7,8,9>|<10,11,12>>;
 
A . B;</langsyntaxhighlight>
{{out}}
<pre> [1 2 3]
Line 3,024 ⟶ 4,473:
[ ]
[32 77 122 167]</pre>
 
 
=={{header|MathCortex}}==
<langsyntaxhighlight lang="mathcortex">
>> A = [2,3; -2,1]
2 3
Line 3,039 ⟶ 4,487:
14 10
2 -2
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
 
The Wolfram Language supports both dot products and element-wise multiplication of matrices.
Line 3,047 ⟶ 4,495:
This computes a dot product:
 
<langsyntaxhighlight lang="mathematica">Dot[{{a, b}, {c, d}}, {{w, x}, {y, z}}]</langsyntaxhighlight>
 
With the following output:
 
<langsyntaxhighlight lang="mathematica">{{a w + b y, a x + b z}, {c w + d y, c x + d z}}</langsyntaxhighlight>
 
This also computes a dot product, using the infix . notation:
 
<langsyntaxhighlight lang="mathematica">{{a, b}, {c, d}} . {{w, x}, {y, z}}</langsyntaxhighlight>
 
This does element-wise multiplication of matrices:
 
<langsyntaxhighlight lang="mathematica">Times[{{a, b}, {c, d}}, {{w, x}, {y, z}}]</langsyntaxhighlight>
 
With the following output:
 
<langsyntaxhighlight lang="mathematica">{{a w, b x}, {c y, d z}}</langsyntaxhighlight>
 
Alternative infix notations '*' and ' ' (space, indicating multiplication):
 
<langsyntaxhighlight lang="mathematica">{{a, b}, {c, d}}*{{w, x}, {y, z}}</langsyntaxhighlight>
<langsyntaxhighlight lang="mathematica">{{a, b}, {c, d}} {{w, x}, {y, z}}</langsyntaxhighlight>
 
In all cases matrices can be fully symbolic or numeric or mixed symbolic and numeric.
Line 3,074 ⟶ 4,522:
as complex numbers:
 
<langsyntaxhighlight lang="mathematica">Dot[{{85, 60, 65}, {54, 99, 33}, {46, 52, 87}}, {{89, 77, 98}, {55, 27, 25}, {80, 68, 85}}]</langsyntaxhighlight>
 
With the following output:
 
<langsyntaxhighlight lang="mathematica">{{16065, 12585, 15355}, {12891, 9075, 10572}, {13914, 10862, 13203}}</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Matlab contains two methods of multiplying matrices: by using the "mtimes(matrix,matrix)" function, or the "*" operator.
 
<langsyntaxhighlight MATLABlang="matlab">>> A = [1 2;3 4]
 
A =
Line 3,109 ⟶ 4,557:
 
19 22
43 50</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">a: matrix([1, 2],
[3, 4],
[5, 6],
Line 3,124 ⟶ 4,572:
[19, 26, 33],
[29, 40, 51],
[39, 54, 69]) */</langsyntaxhighlight>
 
=={{header|Nial}}==
<langsyntaxhighlight 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
=2 4 8 16
Line 3,138 ⟶ 4,586:
=1.3e-15 1. -4.4e-16 -3.3e-16
=0. 0. 1. 4.4e-16
=0. 0. 0. 1.</langsyntaxhighlight>
 
=={{header|Nim}}==
<lang nim>import {{libheader|strfmt}}
<syntaxhighlight lang="nim">import strfmt
 
type Matrix[M, N: static[int]] = array[M, array[N, float]]
 
let a = [[1.0, 1.0, 1.0, 1.0],
Line 3,150 ⟶ 4,599:
[4.0, 16.0, 64.0, 256.0]]
 
let b = [[ 4.0 , -3.0 , 4/3.0, -1/4.0 ],
[-13/3.0, 19/4.0, -7/3.0, 11/24.0],
[ 3/2.0, -2.0 , 7/6.0, -1/4.0 ],
[ -1/6.0, 1/4.0, -1/6.0, 1/24.0]]
 
Line 3,162 ⟶ 4,611:
result.add "])"
 
proc `*`[M, P, N](a: Matrix[M, P]; b: Matrix[P, N]): Matrix[M, N] =
for i in result.low .. result.high:
for j in result[0].low .. result[0].high:
Line 3,171 ⟶ 4,620:
echo b
echo a * b
echo b * a</langsyntaxhighlight>
 
{{out}}
<pre>([ 1.00 1.00 1.00 1.00]
[ 2.00 4.00 8.00 16.00]
[ 3.00 9.00 27.00 81.00]
[ 4.00 16.00 64.00 256.00])
([ 4.00 -3.00 1.33 -0.25]
[ -4.33 4.75 -2.33 0.46]
[ 1.50 -2.00 1.17 -0.25]
[ -0.17 0.25 -0.17 0.04])
([ 1.00 0.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 0.00 1.00])
([ 1.00 0.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 -0.00 1.00])</pre>
 
=={{header|OCaml}}==
 
This version works on arrays of arrays of ints:
<langsyntaxhighlight lang="ocaml">let matrix_multiply x y =
let x0 = Array.length x
and y0 = Array.length y in
Line 3,188 ⟶ 4,655:
done
done;
z</langsyntaxhighlight>
 
# matrix_multiply [|[|1;2|];[|3;4|]|] [|[|-3;-8;3|];[|-2;1;4|]|];;
Line 3,195 ⟶ 4,662:
{{trans|Scheme}}
This version works on lists of lists of ints:
<langsyntaxhighlight lang="ocaml">(* equivalent to (apply map ...) *)
let rec mapn f lists =
assert (lists <> []);
Line 3,211 ⟶ 4,678:
(List.map2 ( * ) row column))
m2)
m1</langsyntaxhighlight>
 
# matrix_multiply [[1;2];[3;4]] [[-3;-8;3];[-2;1;4]];;
Line 3,217 ⟶ 4,684:
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">a = zeros(4);
% prepare the matrix
% 1 1 1 1
Line 3,229 ⟶ 4,696:
endfor
b = inverse(a);
a * b</langsyntaxhighlight>
 
 
=={{header|Ol}}==
This short version works on lists of lists length less than 253 rows and less than 253 columns.
{{trans|Scheme}}
<syntaxhighlight lang="scheme">; short version based on 'apply'
This version works on lists of lists:
<lang ol>
(define (matrix-multiply matrix1 matrix2)
(map
Line 3,244 ⟶ 4,709:
matrix2))
matrix1))
</syntaxhighlight>
</lang>
 
> (matrix-multiply '((1 2) (3 4)) '((-3 -8 3) (-2 1 4)))
((-7 -6 11) (-17 -20 25))
 
This long version works on lists of lists with any matrix dimensions.
<syntaxhighlight lang="scheme">; long version based on recursive cycles
(define (matrix-multiply A B)
(define m (length A))
(define n (length (car A)))
(assert (eq? (length B) n) ===> #true)
(define q (length (car B)))
(define (at m x y)
(lref (lref m x) y))
 
 
(let mloop ((i (- m 1)) (rows #null))
(if (< i 0)
rows
(mloop
(- i 1)
(cons
(let rloop ((j (- q 1)) (r #null))
(if (< j 0)
r
(rloop
(- j 1)
(cons
(let loop ((k 0) (c 0))
(if (eq? k n)
c
(loop (+ k 1) (+ c (* (at A i k) (at B k j))))))
r))))
rows)))))
</syntaxhighlight>
 
Testing large matrices:
<syntaxhighlight lang="scheme">; [372x17] * [17x372]
(define M 372)
(define N 17)
 
; [0 1 2 ... 371]
; [1 2 3 ... 372]
; [2 3 4 ... 373]
; ...
; [16 17 ... 387]
(define A (map (lambda (i)
(iota M i))
(iota N)))
 
; [0 1 2 ... 16]
; [1 2 3 ... 17]
; [2 3 4 ... 18]
; ...
; [371 372 ... 387]
(define B (map (lambda (i)
(iota N i))
(iota M)))
 
(for-each print (matrix-multiply A B))
</syntaxhighlight>
{{Out}}
<pre>
(17090486 17159492 17228498 17297504 17366510 17435516 17504522 17573528 17642534 17711540 17780546 17849552 17918558 17987564 18056570 18125576 18194582)
(17159492 17228870 17298248 17367626 17437004 17506382 17575760 17645138 17714516 17783894 17853272 17922650 17992028 18061406 18130784 18200162 18269540)
(17228498 17298248 17367998 17437748 17507498 17577248 17646998 17716748 17786498 17856248 17925998 17995748 18065498 18135248 18204998 18274748 18344498)
(17297504 17367626 17437748 17507870 17577992 17648114 17718236 17788358 17858480 17928602 17998724 18068846 18138968 18209090 18279212 18349334 18419456)
(17366510 17437004 17507498 17577992 17648486 17718980 17789474 17859968 17930462 18000956 18071450 18141944 18212438 18282932 18353426 18423920 18494414)
(17435516 17506382 17577248 17648114 17718980 17789846 17860712 17931578 18002444 18073310 18144176 18215042 18285908 18356774 18427640 18498506 18569372)
(17504522 17575760 17646998 17718236 17789474 17860712 17931950 18003188 18074426 18145664 18216902 18288140 18359378 18430616 18501854 18573092 18644330)
(17573528 17645138 17716748 17788358 17859968 17931578 18003188 18074798 18146408 18218018 18289628 18361238 18432848 18504458 18576068 18647678 18719288)
(17642534 17714516 17786498 17858480 17930462 18002444 18074426 18146408 18218390 18290372 18362354 18434336 18506318 18578300 18650282 18722264 18794246)
(17711540 17783894 17856248 17928602 18000956 18073310 18145664 18218018 18290372 18362726 18435080 18507434 18579788 18652142 18724496 18796850 18869204)
(17780546 17853272 17925998 17998724 18071450 18144176 18216902 18289628 18362354 18435080 18507806 18580532 18653258 18725984 18798710 18871436 18944162)
(17849552 17922650 17995748 18068846 18141944 18215042 18288140 18361238 18434336 18507434 18580532 18653630 18726728 18799826 18872924 18946022 19019120)
(17918558 17992028 18065498 18138968 18212438 18285908 18359378 18432848 18506318 18579788 18653258 18726728 18800198 18873668 18947138 19020608 19094078)
(17987564 18061406 18135248 18209090 18282932 18356774 18430616 18504458 18578300 18652142 18725984 18799826 18873668 18947510 19021352 19095194 19169036)
(18056570 18130784 18204998 18279212 18353426 18427640 18501854 18576068 18650282 18724496 18798710 18872924 18947138 19021352 19095566 19169780 19243994)
(18125576 18200162 18274748 18349334 18423920 18498506 18573092 18647678 18722264 18796850 18871436 18946022 19020608 19095194 19169780 19244366 19318952)
(18194582 18269540 18344498 18419456 18494414 18569372 18644330 18719288 18794246 18869204 18944162 19019120 19094078 19169036 19243994 19318952 19393910)
</pre>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="ooRexx">/*REXX program multiplies two matrices together, */
/* displays the matrices and the result. */
Signal On syntax
x.=0
a=.matrix~new('A',4,2,1 2 3 4 5 6 7 8) /* create matrix A */
b=.matrix~new('B',2,3,1 2 3 4 5 6) /* create matrix B */
If a~cols<>b~rows Then
Call exit 'Matrices are incompatible for matrix multiplication',
'a~cols='a~cols'<>b~rows='||b~rows
-- say a~name'[2,2] changed from' a~set(2,2,4711) 'to 4711' ; Pull .
c=multMat(a,b) /* multiply A x B */
a~show
b~show
c~show
Exit
 
multMat: Procedure
Use Arg a,b
c.=0
Do i=1 To a~rows
Do j=1 To b~cols
Do k=1 To a~cols
c.i.j=c.i.j+a~element(i,k)*b~element(k,j)
End /*k*/
End /*j*/
End /*i*/
mm=''
Do i=1 To a~rows
Do j=1 To b~cols
mm=mm C.i.j
End /*j*/
End /*i*/
c=.matrix~new('C',a~rows,b~cols,mm)
Return c
/*--------------------------------------------------------------------*/
Exit:
Say arg(1)
Exit
Syntax:
Say 'Syntax raised in line' sigl
Say sourceline(sigl)
Say 'rc='rc '('errortext(rc)')'
Say '***** There was a problem!'
Exit
 
::class Matrix
/********************************************************************
* Matrix is implemented as an array of rows
* where each row is an arryay of elements.
********************************************************************/
::Attribute name
::Attribute rows
::Attribute cols
 
::Method init
expose m name rows cols
Use Arg name,rows,cols,elements
If words(elements)<>(rows*cols) Then Do
Say 'incorrect number of elements ('words(elements)')<>'||(rows*cols)
m=.nil
Return
End
m=.array~new
Do r=1 To rows
ro=.array~new
Do c=1 To cols
Parse Var elements e elements
ro~append(e)
End
m~append(ro)
End
 
::Method element /* get an element's value */
expose m
Use Arg r,c
ro=m[r]
Return ro[c]
 
::Method set /* set an element's value and return its previous */
expose m
Use Arg r,c,new
ro=m[r]
old=ro[c]
ro[c]=new
Return old
 
::Method show /* display the matrix */
expose m name rows cols
z='+'
b6=left('',6)
Say ''
Say b6 copies('-',7) 'matrix' name copies('-',7)
w=0
Do r=1 To rows
ro=m[r]
Do c=1 To cols
x=ro[c]
w=max(w,length(x))
End
End
Say b6 b6 '+'copies('-',cols*(w+1)+1)'+' /* top border */
Do r=1 To rows
ro=m[r]
line='|' right(ro[1],w) /* element of first colsumn */ /* start with long vertical bar */
Do c=2 To cols /* loop for other columns */
line=line right(ro[c],w) /* append the elements */
End /* c */
Say b6 b6 line '|' /* append a long vertical bar. */
End /* r */
Say b6 b6 '+'copies('-',cols*(w+1)+1)'+' /* bottom border */
Return</syntaxhighlight>
{{Out}}
<pre>
------- matrix A -------
+-----+
| 1 2 |
| 3 4 |
| 5 6 |
| 7 8 |
+-----+
 
------- matrix B -------
+-------+
| 1 2 3 |
| 4 5 6 |
+-------+
 
------- matrix C -------
+----------+
| 9 12 15 |
| 19 26 33 |
| 29 40 51 |
| 39 54 69 |
+----------+ </pre>
 
 
 
=={{header|OxygenBasic}}==
Generic MatMul:
<syntaxhighlight lang="text">
'generic with striding pointers
'def typ float
typedef float typ
'
function MatMul(typ *r,*a,*b, int n=4) 'NxN MATRIX : N=1..
============================================================
int ystep=sizeof typ
int xstep=n*sizeof typ
int i,j,k
sys px
for i=1 to n
px=@a
for j=1 to n
r=0
for k=1 to n
r+=(a*b)
@a+=xstep
@b+=ystep
next
@r+=ystep
px+=ystep
@a=px
@b-=xstep
next
@a-=xstep
@b+=xstep
next
end function
</syntaxhighlight>
 
When using matrices in Video graphics, speed is important. Here is a matrix multiplier written in OxygenBasics's x86 Assembly code.
<langsyntaxhighlight lang="oxygenbasic">
'Example of matrix layout mapped to an array of 4x4 cells
'
Line 3,365 ⟶ 5,077:
 
Print ShowMatrix C,n
</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<syntaxhighlight lang ="parigp">M*N</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 3,375 ⟶ 5,087:
This function takes two references to arrays of arrays and returns the product as a reference to a new anonymous array of arrays.
 
<langsyntaxhighlight lang="perl">sub mmult
{
our @a; local *a = shift;
Line 3,409 ⟶ 5,121:
 
$c = mmult(\@a,\@b);
display($c)</langsyntaxhighlight>
{{out}}
<pre> -7 -6 11
-17 -20 25</pre>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
 
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
{{trans|Perl 5}}
<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: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">ha</span><span style="color: #0000FF;">,</span><span style="color: #000000;">wa</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hb</span><span style="color: #0000FF;">,</span><span style="color: #000000;">wb</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">apply</span><span style="color: #0000FF;">({</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]},</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">)</span>
{{works with|Rakudo|2015-09-22}}
<span style="color: #008080;">if</span> <span style="color: #000000;">wa</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">hb</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"invalid aguments"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
 
<span style="color: #004080;">sequence</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">wb</span><span style="color: #0000FF;">),</span><span style="color: #000000;">ha</span><span style="color: #0000FF;">)</span>
There are three ways in which this example differs significantly from the original Perl&nbsp;5 code. These are not esoteric differences; all three of these features typically find heavy use in Perl&nbsp;6.
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">ha</span> <span style="color: #008080;">do</span>
 
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">wb</span> <span style="color: #008080;">do</span>
First, we can use a real signature that can bind two arrays as arguments, because the default in Perl&nbsp;6 is not to flatten arguments unless the signature specifically requests it.
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">wa</span> <span style="color: #008080;">do</span>
We don't need to pass the arrays with backslashes because the binding choice is made lazily
<span style="color: #000000;">c</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">b</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span>
by the signature itself at run time; in Perl&nbsp;5 this choice must be made at compile time.
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
Also, we can bind the arrays to formal parameters that are really lexical variable names; in Perl&nbsp;5 they can only be bound to global array objects (via a typeglob assignment).
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
Second, we use the X cross operator in conjunction with a two-parameter closure to avoid writing
<span style="color: #008080;">return</span> <span style="color: #000000;">c</span>
nested loops. The X cross operator, along with Z, the zip operator, is a member of a class of operators that expect lists on both sides, so we call them "list infix" operators. We tend to define these operators using capital letters so that they stand out visually from the lists on both sides. The cross operator makes every possible combination of the one value from the first list followed by one value from the second. The right side varies most rapidly, just like an inner loop. (The X and Z operators may both also be used as meta-operators, Xop or Zop, distributing some other operator "op" over their generated list. All metaoperators in Perl&nbsp;6 may be applied to user-defined operators as well.)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
Third is the use of prefix <tt>^</tt> to generate a list of numbers in a range. Here it is
<span style="color: #7060A8;">ppOpt</span><span style="color: #0000FF;">({</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_IntFmt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%3d"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_FltFmt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%3.0f"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_IntCh</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">})</span>
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.
 
<span style="color: #008080;">constant</span> <span style="color: #000000;">A</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span> <span style="color: #0000FF;">{</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span> <span style="color: #0000FF;">},</span>
<lang perl6>sub mmult(@a,@b) {
<span style="color: #0000FF;">{</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span> <span style="color: #0000FF;">},</span>
my @p;
<span style="color: #0000FF;">{</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span> <span style="color: #0000FF;">},</span>
for ^@a X ^@b[0] -> ($r, $c) {
<span style="color: #0000FF;">{</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span> <span style="color: #0000FF;">}},</span>
@p[$r][$c] += @a[$r][$_] * @b[$_][$c] for ^@b;
<span style="color: #000000;">B</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span> <span style="color: #0000FF;">{</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span> <span style="color: #0000FF;">},</span>
}
<span style="color: #0000FF;">{</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span> <span style="color: #0000FF;">}}</span>
@p;
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">matrix_mul</span><span style="color: #0000FF;">(</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;">constant</span> <span style="color: #000000;">C</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span> <span style="color: #0000FF;">{</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span> <span style="color: #0000FF;">},</span>
my @a = [1, 1, 1, 1],
<span style="color: #0000FF;">{</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">16</span> <span style="color: #0000FF;">},</span>
[2, 4, 8, 16],
<span style="color: #0000FF;">{</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">27</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">81</span> <span style="color: #0000FF;">},</span>
[3, 9, 27, 81],
<span style="color: #0000FF;">{</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">16</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">64</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">256</span> <span style="color: #0000FF;">}},</span>
[4, 16, 64, 256];
<span style="color: #000000;">D</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span> <span style="color: #0000FF;">{</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">/</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span> <span style="color: #000000;">4</span> <span style="color: #0000FF;">},</span>
 
<span style="color: #0000FF;">{-</span><span style="color: #000000;">13</span><span style="color: #0000FF;">/</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">19</span><span style="color: #0000FF;">/</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">7</span><span style="color: #0000FF;">/</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">11</span><span style="color: #0000FF;">/</span><span style="color: #000000;">24</span> <span style="color: #0000FF;">},</span>
my @b = [ 4 , -3 , 4/3, -1/4 ],
<span style="color: #0000FF;">{</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">/</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span> <span style="color: #000000;">4</span> <span style="color: #0000FF;">},</span>
[-13/3, 19/4, -7/3, 11/24],
<span style="color: #0000FF;">{</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">24</span> <span style="color: #0000FF;">}}</span>
[ 3/2, -2 , 7/6, -1/4 ],
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">matrix_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">C</span><span style="color: #0000FF;">,</span><span style="color: #000000;">D</span><span style="color: #0000FF;">))</span>
[ -1/6, 1/4, -1/6, 1/24];
 
<span style="color: #008080;">constant</span> <span style="color: #000000;">F</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">},</span>
.say for mmult(@a,@b);</lang>
<span style="color: #0000FF;">{</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">},</span>
 
<span style="color: #0000FF;">{</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">}},</span>
<span style="color: #000000;">G</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">}}</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">matrix_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">F</span><span style="color: #0000FF;">,</span><span style="color: #000000;">G</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">H</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">}},</span>
<span style="color: #000000;">I</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">}}</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">matrix_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">H</span><span style="color: #0000FF;">,</span><span style="color: #000000;">I</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">R</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{-</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">}}</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">matrix_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">R</span><span style="color: #0000FF;">,</span><span style="color: #000000;">R</span><span style="color: #0000FF;">))</span>
<span style="color: #000080;font-style:italic;">-- large matrix example from OI:</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">row</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">l</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">J</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;">16</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">),</span><span style="color: #000000;">371</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>
<!--</syntaxhighlight>-->
{{out}}
<pre>[1 0 0 0]
{{ 9, 12, 15},
[0 1 0 0]
{ 19, 26, 33},
[0 0 1 0]
{ 29, 40, 51},
[0 0 0 1]</pre>
{ 39, 54, 69}}
 
{{ 1, 0, 0, 0},
Note that these are not rounded values, but exact, since all the math was done in rationals.
{ 0, 1, 0, 0},
Hence we need not rely on format tricks to hide floating-point inaccuracies.
{ 0, 0, 1, 0},
 
{ 0, 0, 0, 1}}
Just for the fun of it, here's a functional version that uses no temp variables or side effects.
{{ 1, 2, 3},
Some people will find this more readable and elegant, and others will, well, not.
{ 4, 5, 6},
 
{ 7, 8, 9}}
<lang perl6>sub mmult(\a,\b) {
{{ 19, 22},
[
{ 43, 50}}
for ^a -> \r {
{{ 0, [1},
{ -1, 0}}
for ^b[0] -> \c {
{{17090486,17159492, `...`, 18125576,18194582},
[+] a[r;^b] Z* b[^b;c]
{17159492,17228870, `...`, 18200162,18269540},
}
`...`,
]
{18125576,18200162, `...`, 19244366,19318952},
}
{18194582,18269540, `...`, 19318952,19393910}}
]
}</langpre>
Note that you get some "-0" in the second result under p2js due to differences in rounding behaviour between JavaScript and desktop/Phix.
 
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.
 
=={{header|Phix}}==
Copy of [[Matrix_multiplication#Euphoria|Euphoria]]
<lang Phix>function matrix_mul(sequence a, sequence b)
sequence c
if length(a[1]) != length(b) then
return 0
else
c = repeat(repeat(0,length(b[1])),length(a))
for i=1 to length(a) do
for j=1 to length(b[1]) do
for k=1 to length(a[1]) do
c[i][j] += a[i][k]*b[k][j]
end for
end for
end for
return c
end if
end function</lang>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de matMul (Mat1 Mat2)
(mapcar
'((Row)
Line 3,508 ⟶ 5,223:
(matMul
'((1 2 3) (4 5 6))
'((6 -1) (3 2) (0 -3)) )</langsyntaxhighlight>
{{out}}
<pre>-> ((12 -6) (39 -12))</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Matrix multiplication of A by B, yielding C */
MMULT: procedure (a, b, c);
Line 3,537 ⟶ 5,252:
end;
end MMULT;
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
 
<langsyntaxhighlight lang="pop11">define matmul(a, b) -> c;
lvars ba = boundslist(a), bb = boundslist(b);
lvars i, i0 = ba(1), i1 = ba(2);
Line 3,563 ⟶ 5,278:
endfor;
endfor;
enddefine;</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function multarrays($a, $b) {
$n,$m,$p = ($a.Count - 1), ($b.Count - 1), ($b[0].Count - 1)
if ($a[0].Count -ne $b.Count) {throw "Multiplication impossible"}
$c = @(0)*($ba[0].Count)
foreach ($i in 0..$n) {
$c[$i] = foreach ($j in 0..$p) {
Line 3,599 ⟶ 5,315:
"`$a * `$c ="
show (multarrays $a $c)
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 3,626 ⟶ 5,342:
{{trans|Scheme}}
{{works with|SWI Prolog|5.9.9}}
<langsyntaxhighlight lang="prolog">% SWI-Prolog has transpose/2 in its clpfd library
:- use_module(library(clpfd)).
 
Line 3,636 ⟶ 5,352:
% 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).
mm_helper(M2, I1, M3) :- maplist(dot(I1), M2, M3).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
Matrices represented as integer arrays with rows in the first dimension and columns in the second.
<langsyntaxhighlight PureBasiclang="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
Line 3,661 ⟶ 5,378:
ProcedureReturn #False ;multiplication not performed, dimensions invalid
EndIf
EndProcedure</langsyntaxhighlight>
Additional code to demonstrate use.
<langsyntaxhighlight PureBasiclang="purebasic">DataSection
Data.i 2,3 ;matrix a (#rows, #cols)
Data.i 1,2,3, 4,5,6 ;elements by row
Line 3,716 ⟶ 5,433:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>matrix a: (2, 3)
Line 3,732 ⟶ 5,449:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">a=((1, 1, 1, 1), # matrix A #
(2, 4, 8, 16),
(3, 9, 27, 81),
Line 3,769 ⟶ 5,486:
print '%8.2f '%val,
print ']'
print ')'</langsyntaxhighlight>
 
Another one, {{trans|Scheme}}
<langsyntaxhighlight lang="python">from operator import mul
 
def matrixMul(m1, m2):
Line 3,781 ⟶ 5,498:
sum(map(mul, row, column)),
*m2),
m1)</langsyntaxhighlight>
 
Using list comprehensions, multiplying matrices represented as lists of lists. (Input is not validated):
<langsyntaxhighlight 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]</langsyntaxhighlight>
 
Another one, use numpy the most popular array package for python
<langsyntaxhighlight lang="python">
import numpy as np
np.dot(a,b)
#or if a is an array
a.dot(b)</langsyntaxhighlight>
 
=={{header|R}}==
<syntaxhighlight lang ="r">a %*% b</langsyntaxhighlight>
 
=={{header|Racket}}==
{{trans|Scheme}}
 
<langsyntaxhighlight lang="racket">
#lang racket
(define (m-mult m1 m2)
Line 3,808 ⟶ 5,525:
(m-mult '((1 2) (3 4)) '((5 6) (7 8)))
;; -> '((19 22) (43 50))
</syntaxhighlight>
</lang>
 
Alternative:
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
(matrix* (matrix [[1 2] [3 4]]) (matrix [[5 6] [7 8]]))
;; -> (array #[#[19 22] #[43 50]])
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
{{trans|Perl 5}}
 
{{works with|Rakudo|2015-09-22}}
 
There are three ways in which this example differs significantly from the original Perl&nbsp;5 code. These are not esoteric differences; all three of these features typically find heavy use in Raku.
 
First, we can use a real signature that can bind two arrays as arguments, because the default in Raku is not to flatten arguments unless the signature specifically requests it.
We don't need to pass the arrays with backslashes because the binding choice is made lazily
by the signature itself at run time; in Perl&nbsp;5 this choice must be made at compile time.
Also, we can bind the arrays to formal parameters that are really lexical variable names; in Perl&nbsp;5 they can only be bound to global array objects (via a typeglob assignment).
 
Second, we use the X cross operator in conjunction with a two-parameter closure to avoid writing
nested loops. The X cross operator, along with Z, the zip operator, is a member of a class of operators that expect lists on both sides, so we call them "list infix" operators. We tend to define these operators using capital letters so that they stand out visually from the lists on both sides. The cross operator makes every possible combination of the one value from the first list followed by one value from the second. The right side varies most rapidly, just like an inner loop. (The X and Z operators may both also be used as meta-operators, Xop or Zop, distributing some other operator "op" over their generated list. All metaoperators in Raku may be applied to user-defined operators as well.)
 
Third is the use of prefix <tt>^</tt> to generate a list of numbers in a range. Here it is
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.
 
<syntaxhighlight lang="raku" line>sub mmult(@a,@b) {
my @p;
for ^@a X ^@b[0] -> ($r, $c) {
@p[$r][$c] += @a[$r][$_] * @b[$_][$c] for ^@b;
}
@p;
}
 
my @a = [1, 1, 1, 1],
[2, 4, 8, 16],
[3, 9, 27, 81],
[4, 16, 64, 256];
 
my @b = [ 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];
 
.say for mmult(@a,@b);</syntaxhighlight>
 
{{out}}
<pre>[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]</pre>
 
Note that these are not rounded values, but exact, since all the math was done in rationals.
Hence we need not rely on format tricks to hide floating-point inaccuracies.
 
Just for the fun of it, here's a functional version that uses no temp variables or side effects.
Some people will find this more readable and elegant, and others will, well, not.
 
<syntaxhighlight lang="raku" line>sub mmult(\a,\b) {
[
for ^a -> \r {
[
for ^b[0] -> \c {
[+] a[r;^b] Z* b[^b;c]
}
]
}
]
}</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.
 
For conciseness, the above could be written as:
 
<syntaxhighlight lang="raku" line>multi infix:<×> (@A, @B) {
@A.map: -> @a { do [+] @a Z× @B[*;$_] for ^@B[0] }
}</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.
 
{{works with|Rakudo|2022.07-3}}
 
Here is a more functional version, expressing the product of two matrices as the cross dot product of the first matrix with the transpose of the second :
 
<syntaxhighlight lang="raku" line>sub infix:<·> { [+] @^a Z* @^b }
sub infix:<×>(@A, @B) { (@A X· [Z] @B).rotor(@B) }
</syntaxhighlight>
 
=={{header|Rascal}}==
<langsyntaxhighlight Rascallang="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)){
p = {<x1,y1,x2,y2, v1*v2> | <x1,y1,v1> <- matrix1, <x2,y2,v2> <- matrix2};
Line 3,839 ⟶ 5,638:
<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>
};</langsyntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program multipliescalculates twothe matricesKronecker together,product displays the matricesof and the resultstwo arbitrary size matrices. */
Signal On syntax
x.=; x.1=1 2 /*╔═══════════════════════════════════╗*/
x.=0
x.2=3 4 /*║ As none of the matrix values have ║*/
amat=4X2 1 2 3 4 x.3=5 6 7 8 /*║ a sign, quotesdefine aren'tA needed.matrix size and elements */
bmat=2X3 1 2 3 4 5 x.4=76 8 /* " B " " " " /*╚═══════════════════════════════════╝*/
Call makeMat 'A',amat do r=1 while x.r\=='' /*build theconstruct "A" matrix from X.elements numbers.*/
Call makeMat 'B',bmat /* " do c=1 while x.r\==''; B parse var x.r" a.r.c x.r; " " end /*c*/
If cols.A<>rows.B Then
end /*r*/
Call exit 'Matrices are incompatible for matrix multiplication',
Arows=r-1 /*adjust the number of rows (DO loop).*/
'cols.A='cols.A'<>rows.B='rows.B
Acols=c-1 /* " " " " cols " " .*/
Call multMat /* multiply A x B */
y.=; y.1=1 2 3
Call showMat 'A',amat /* display matrix A */
y.2=4 5 6
Call showMat 'B',bmat /* " do r=1 while y.r\=='' " B /*build the "B" matrix from Y. numbers.*/
Call showMat 'C',mm /* " do c=1 while y.r\==''; parse var" C y.r b.r.c y.r; end /*c*/
Exit
end /*r*/
/*--------------------------------------------------------------------*/
Brows=r-1 /*adjust the number of rows (DO loop).*/
makeMat:
Bcols=c-1 /* " " " " cols " " */
Parse Arg what,size elements /*elements: e.1.1 e.1.2 - e.rows cols*/
c.=0; w=0 /*W is max width of an matrix element.*/
Parse Var size rows 'X' cols
do i=1 for Arows /*multiply matrix A and B ───► C */
x.what.shape=rows cols
do j=1 for Bcols
Parse Value rows cols With rows.what cols.what
do k=1 for Acols; c.i.j=c.i.j + a.i.k * b.k.j
n=0
w=max(w, length(c.i.j))
Do r=1 To rows
end /*k*/ /* ↑ */
Do c=1 To cols
end /*j*/ /* └──◄─── maximum width of elements. */
end /*i*/n=n+1
element=word(elements,n)
x.what.r.c=element
End
End
Return
/*--------------------------------------------------------------------*/
multMat:
/* x.C.*.* = x.A.*.* x x.B.*.* */
Do i=1 To rows.A
Do j=1 To cols.B
Do k=1 To cols.A
x.C.i.j=x.C.i.j+x.A.i.k*x.B.k.j
End /*k*/
End /*j*/
End /*i*/
mm=rows.A||'X'||cols.B
Do i=1 To rows.A
Do j=1 To cols.B
mm=mm x.C.i.j
End /*j*/
End /*i*/
Call makeMat 'C',mm
Return
/*--------------------------------------------------------------------*/
showMat:
Parse Arg what,size .
Parse Var size rows 'X' cols
z='+'
b6=left('',6)
Say ''
Say b6 copies('-',7) 'matrix' what copies('-',7)
w=0
Do r=1 To rows
Do c=1 To cols
w=max(w,length(x.what.r.c))
End
End
Say b6 b6 '+'copies('-',cols*(w+1)+1)'+' /* top border */
Do r=1 To rows
line='|' right(x.what.r.1,w) /* element of first colsumn */ /* start with long vertical bar */
Do c=2 To cols /* loop for other columns */
line=line right(x.what.r.c,w) /* append the elements */
End /* c */
Say b6 b6 line '|' /* append a long vertical bar. */
End /* r */
Say b6 b6 '+'copies('-',cols*(w+1)+1)'+' /* bottom border */
Return
exit:
Say arg(1)
Exit
 
Syntax:
call showMatrix 'A', Arows, Acols /*display matrix A ───► the terminal.*/
Say 'Syntax raised in line' sigl
call showMatrix 'B', Brows, Bcols /* " " B ───► " " */
Say sourceline(sigl)
call showMatrix 'C', Arows, Bcols /* " " C ───► " " */
Say 'rc='rc '('errortext(rc)')'
exit /*stick a fork in it, we're all done. */
Say '***** There was a problem!'
/*──────────────────────────────────────────────────────────────────────────────────────*/
Exit</syntaxhighlight>
showMatrix: parse arg mat,rows,cols; say; say center(mat 'matrix', cols*(w+1) +4, "─")
{{out|output|text=&nbsp; when using the internal default input:}}
do r=1 for rows; _=
do c=1 for cols; _=_ right(value(mat'.'r"."c), w); end; say _
end /*r*/
return</lang>
'''output'''
<pre>
------- matrix A -------
─A matrix─
+-----+
1 2
| 1 2 |
3 4
| 3 4 |
5 6
| 5 6 |
7 8
| 7 8 |
+-----+
 
------- matrix B -------
──B matrix───
1 2 3 +-------+
4 5 6 | 1 2 3 |
| 4 5 6 |
+-------+
 
------- matrix C -------
──C matrix───
+----------+
9 12 15
| 9 12 15 |
19 26 33
| 19 26 33 |
29 40 51
| 29 40 51 |
39 54 69
| 39 54 69 |
+----------+
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
n = 3
Line 3,917 ⟶ 5,768:
see nl
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,923 ⟶ 5,774:
456
789
</pre>
 
=={{header|RPL}}==
The <code>*</code> operator can multiply numbers of any kind together, matrices - and even lists in latest RPL versions.
[[1 2 3][4 5 6]] [[3 1][4 1][5 9]] *
{{out}}
<pre>
1: [[ 26 30 ]
[ 62 63 ]]
</pre>
 
=={{header|Ruby}}==
Using 'matrix' from the standard library:
<langsyntaxhighlight lang="ruby">require 'matrix'
 
Matrix[[1, 2],
[3, 4]] * Matrix[[-3, -8, 3],
[-2, 1, 4]]</langsyntaxhighlight>
{{out}}
Matrix[[-7, -6, 11], [-17, -20, 25]]
 
Version for lists: {{trans|Haskell}}
<langsyntaxhighlight lang="ruby">def matrix_mult(a, b)
a.map do |ar|
b.transpose.map do{ |bc| ar.zip(bc).map{ |x| x.inject(&:*) }.sum }
ar.zip(bc).map(&:*).inject(&:+)
end
end
end</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
struct Matrix {
dat: [[f32; 3]; 3]
Line 4,005 ⟶ 5,863:
}
 
</syntaxhighlight>
</lang>
 
=={{header|S-lang}}==
<syntaxhighlight lang="c">% Matrix multiplication is a built-in with the S-Lang octothorpe operator.
variable A = [1,2,3,4,5,6];
reshape(A, [2,3]); % reshape 1d array to 2 rows, 3 columns
printf("A is %S\n", A); print(A);
 
variable B = [1:6]; % index range, 1 to 6 same as above in A
reshape(B, [3,2]); % reshape to 3 rows, 2 columns
printf("\nB is %S\n", B); print(B);
 
printf("\nA # B is %S\n", A#B);
print(A#B);
 
% Multiply binary operator is different, dimensions need to be equal
reshape(B, [2,3]);
printf("\nA * B is %S (with reshaped B to match A)\n", A*B);
print(A*B);</syntaxhighlight>
 
{{out}}
<pre>prompt$ slsh matrix_mul.sl
A is Integer_Type[2,3]
1 2 3
4 5 6
 
B is Integer_Type[3,2]
1 2
3 4
5 6
 
A # B is Float_Type[2,2]
22.0 28.0
49.0 64.0
 
A * B is Integer_Type[2,3] (with B reshaped to match A)
1 4 9
16 25 36</pre>
 
=={{header|Scala}}==
Line 4,011 ⟶ 5,906:
Assuming an array of arrays representation:
 
<langsyntaxhighlight lang="scala">def mult[A](a: Array[Array[A]], b: Array[Array[A]])(implicit n: Numeric[A]) = {
import n._
for (row <- a)
yield for(col <- b.transpose)
yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
}</langsyntaxhighlight>
 
For any subclass of <code>Seq</code> (which does not include Java-specific arrays):
 
<langsyntaxhighlight 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]] = {
import n._
Line 4,026 ⟶ 5,921:
yield for(col <- b.transpose)
yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
}</langsyntaxhighlight>
 
Examples:
Line 4,056 ⟶ 5,951:
{{trans|Common Lisp}}
This version works on lists of lists:
<langsyntaxhighlight lang="scheme">(define (matrix-multiply matrix1 matrix2)
(map
(lambda (row)
Line 4,063 ⟶ 5,958:
(apply + (map * row column)))
matrix2))
matrix1))</langsyntaxhighlight>
 
> (matrix-multiply '((1 2) (3 4)) '((-3 -8 3) (-2 1 4)))
Line 4,069 ⟶ 5,964:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const type: matrix is array array float;
 
const func matrix: (in matrix: left) * (in matrix: right) is func
Line 4,094 ⟶ 5,989:
end for;
end if;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#mmult]
Line 4,105 ⟶ 6,000:
The SequenceL definition mirrors that definition more or less exactly:
 
<langsyntaxhighlight lang="sequencel">matmul(A(2), B(2)) [i,j] :=
let k := 1...size(B);
in sum( A[i,k] * B[k,j] );
Line 4,116 ⟶ 6,011:
[-2, 1, 4]];
test := matmul(a, b);</langsyntaxhighlight>
 
It can be written a little more simply using the all keyword:
 
<langsyntaxhighlight lang="sequencel">matmul(A(2), B(2)) [i,j] := sum( A[i,all] * B[all,j] );</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func matrix_multi(a, b) {
var m = [[]]
for r in ^a {
Line 4,149 ⟶ 6,044:
for line in matrix_multi(a, b) {
say line.map{|i|'%3d' % i }.join(', ')
}</langsyntaxhighlight>
{{out}}
<pre> 9, 12, 15
Line 4,160 ⟶ 6,055:
{{works with|OpenAxiom}}
{{works with|Axiom}}
<langsyntaxhighlight SPADlang="spad">(1) -> A:=matrix [[1,2],[3,4],[5,6],[7,8]]
 
+1 2+
Line 4,185 ⟶ 6,080:
| |
+39 54 69+
Type: Matrix(Integer)</langsyntaxhighlight>
 
Domain:[http://fricas.github.io/api/Matrix.html?highlight=matrix Matrix(R)]
 
=={{header|SQL}}==
<langsyntaxhighlight lang="sql">CREATE TABLE a (x integer, y integer, e real);
CREATE TABLE b (x integer, y integer, e real);
 
Line 4,209 ⟶ 6,104:
INTO TABLE c
FROM a AS lhs, b AS rhs
WHERE lhs.x = 0 AND rhs.y = 0;</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">structure MatrixIMatrix = struct
fun dot(x,y) = Vector.foldli (fn (i,xi,agg) => agg+xi*Vector.sub(y,i)) 0 x
local
fun x*y =
open Array2
let
fun dot(x,y) = Vector.foldli (fn (i,xi,agg) => agg+xi*Vector.sub(y,i)) 0 x
open Array2
in
in
val fromList = fromList
fun x*y = tabulate ColMajor (nRows x, nCols y, fn (i,j) => dot(row(x,i),column(y,j)))
end
end;
(* for display *)
fun toList a =
let
List.tabulate(nRows a, fn i => List.tabulate(nCols a, fn j => sub(a,i,j)))
open Array2
end
in
end;
List.tabulate(nRows a, fn i => List.tabulate(nCols a, fn j => sub(a,i,j)))
end;
(* example *)
let
let open Matrix
open IMatrix
val m1 = fromList [[1,2],[3,4]]
val m2m1 = Array2.fromList [[~31,~8,32],[~2,13,4]]
val m2 = Array2.fromList [[~3,~8,3],[~2,1,4]]
in
toList (m1*m2)
end;</langsyntaxhighlight>
'''Output:'''
<langsyntaxhighlight lang="sml">val it = [[~7,~6,11],[~17,~20,25]] : int list list</langsyntaxhighlight>
 
=={{header|Stata}}==
=== Stata matrices ===
<langsyntaxhighlight 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 c=a*b
Line 4,243 ⟶ 6,144:
c1 c2 c3 c4
r1 3 1 3 5
r2 9 4 6 11</langsyntaxhighlight>
=== Mata ===
<langsyntaxhighlight lang="stata">: a=1,2,3\4,5,6
: b=1,1,0,0\1,0,0,1\0,0,1,1
: a*b
Line 4,252 ⟶ 6,153:
1 | 3 1 3 5 |
2 | 9 4 6 11 |
+---------------------+</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">@inlinable
public func matrixMult<T: Numeric>(_ m1: [[T]], _ m2: [[T]]) -> [[T]] {
let n = m1[0].count
let m = m1.count
let p = m2[0].count
 
guard m != 0 else {
return []
}
 
precondition(n == m2.count)
 
var ret = Array(repeating: Array(repeating: T.zero, count: p), count: m)
 
for i in 0..<m {
for j in 0..<p {
for k in 0..<n {
ret[i][j] += m1[i][k] * m2[k][j]
}
}
}
 
return ret
}
 
@inlinable
public func printMatrix<T>(_ matrix: [[T]]) {
guard !matrix.isEmpty else {
print()
 
return
}
 
let rows = matrix.count
let cols = matrix[0].count
 
for i in 0..<rows {
for j in 0..<cols {
print(matrix[i][j], terminator: " ")
}
 
print()
}
}
 
let m1 = [
[6.5, 2, 3],
[4.5, 1, 5]
]
 
let m2 = [
[10.0, 16, 23, 50],
[12, -8, 16, -4],
[70, 60, -1, -2]
]
 
let m3 = matrixMult(m1, m2)
 
printMatrix(m3)</syntaxhighlight>
 
{{out}}
 
<pre>299.0 268.0 178.5 311.0
407.0 364.0 114.5 211.0 </pre>
 
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
operator (A matmul B)
$A -> \[i](
$B(1) -> \[j](@: 0;
1..$B::length -> @: $@ + $A($i;$) * $B($;$j);
$@ !\) !
\) !
end matmul
 
templates printMatrix&{w:}
templates formatN
@: [];
$ -> #
'$@ -> $::length~..$w -> ' ';$@(last..1:-1)...;' !
when <1..> do ..|@: $ mod 10; $ ~/ 10 -> #
when <=0?($@ <[](0)>)> do ..|@: 0;
end formatN
$... -> '|$(1) -> formatN;$(2..last)... -> ', $ -> formatN;';|
' !
end printMatrix
 
def a: [[1, 2, 3], [4, 5, 6]];
'a:
' -> !OUT::write
$a -> printMatrix&{w:2} -> !OUT::write
 
def b: [[0, 1], [2, 3], [4, 5]];
'
b:
' -> !OUT::write
$b -> printMatrix&{w:2} -> !OUT::write
'
axb:
' -> !OUT::write
($a matmul $b) -> printMatrix&{w:2} -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
a:
| 1, 2, 3|
| 4, 5, 6|
 
b:
| 0, 1|
| 2, 3|
| 4, 5|
 
axb:
|16, 22|
|34, 49|
</pre>
 
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
namespace path ::tcl::mathop
proc matrix_multiply {a b} {
Line 4,275 ⟶ 6,296:
}
return $temp
}</langsyntaxhighlight>
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}}]
Line 4,283 ⟶ 6,304:
=={{header|TI-83 BASIC}}==
Store your matrices in <tt>[A]</tt> and <tt>[B]</tt>.
<syntaxhighlight lang ="ti83b">Disp [A]*[B]</langsyntaxhighlight>
An error will show if the matrices have invalid dimensions for multiplication.
<br><br>'''Other way:''' enter directly your matrices:
<langsyntaxhighlight lang="ti83b">[[1,2][3,4][5,6][7,8]]*[[1,2,3][4,5,6]]</langsyntaxhighlight>
{{out}}
[[9 12 15]
Line 4,297 ⟶ 6,318:
{{trans|Mathematica}}
 
<langsyntaxhighlight lang="ti89b">[1,2; 3,4; 5,6; 7,8] → m1
[1,2,3; 4,5,6] → m2
m1 * m2</langsyntaxhighlight>
 
Or without the variables:
 
<langsyntaxhighlight lang="ti89b">[1,2; 3,4; 5,6; 7,8] * [1,2,3; 4,5,6]</langsyntaxhighlight>
 
The result (without prettyprinting) is:
 
<langsyntaxhighlight lang="ti89b">[[9,12,15][19,26,33][29,40,51][39,54,69]]</langsyntaxhighlight>
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
 
 
MainModule: {
_start: (λ (with n 5
A (for i in Range(n) project (for k in Range(n) project k))
B (for i in Range(n) project (for k in Range(n) project (- n k)))
C (for i in Range(n) project (for k in Range(n) project 0))
 
(for i in Range( n ) do
(for j in Range( n ) do
(for k in Range( n ) do
(+= (get (get C i) j) (* (get (get A i) k) (get (get B k) j)))
)))
(lout C))
)
}</syntaxhighlight>{{out}}
<pre>
[[50, 40, 30, 20, 10],
[50, 40, 30, 20, 10],
[50, 40, 30, 20, 10],
[50, 40, 30, 20, 10],
[50, 40, 30, 20, 10]]
</pre>
 
=={{header|UNIX Shell}}==
<langsyntaxhighlight lang="bash">
#!/bin/bash
 
Line 4,494 ⟶ 6,541:
echo
echo
</syntaxhighlight>
</lang>
 
=={{header|Ursala}}==
Line 4,502 ⟶ 6,549:
the built in rational number type.
 
<langsyntaxhighlight Ursalalang="ursala">#import rat
 
a =
Line 4,524 ⟶ 6,571:
#cast %qLL
 
test = mmult(a,b)</langsyntaxhighlight>
{{out}}
<pre><
Line 4,534 ⟶ 6,581:
=={{header|VBA}}==
Using Excel. The resulting matrix should be smaller than 5461 elements.
<langsyntaxhighlight lang="vb">Function matrix_multiplication(a As Variant, b As Variant) As Variant
matrix_multiplication = WorksheetFunction.MMult(a, b)
End Function</langsyntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Dim matrix1(2,2)
matrix1(0,0) = 3 : matrix1(0,1) = 7 : matrix1(0,2) = 4
Line 4,558 ⟶ 6,606:
Next
End Sub
</syntaxhighlight>
</lang>
 
{{Out}}
Line 4,568 ⟶ 6,616:
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang="vfp">
LOCAL ARRAY a[4,2], b[2,3], c[4,3]
CLOSE DATABASES ALL
Line 4,611 ⟶ 6,659:
ENDIF
ENDPROC
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
{{libheader|Wren-matrix}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./matrix" for Matrix
import "./fmt" for Fmt
 
var a = Matrix.new([
[1, 2],
[3, 4],
[5, 6],
[7, 8]
])
 
var b = Matrix.new([
[1, 2, 3],
[4, 5, 6]
])
 
System.print("Matrix A:\n")
Fmt.mprint(a, 2, 0)
System.print("\nMatrix B:\n")
Fmt.mprint(b, 2, 0)
System.print("\nMatrix A x B:\n")
Fmt.mprint(a * b, 3, 0)</syntaxhighlight>
 
{{out}}
<pre>
Matrix A:
 
| 1 2|
| 3 4|
| 5 6|
| 7 8|
 
Matrix B:
 
| 1 2 3|
| 4 5 6|
 
Matrix A x B:
 
| 9 12 15|
| 19 26 33|
| 29 40 51|
| 39 54 69|
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">proc Mat4x1Mul(M, V); \Multiply matrix M times column vector V
real M, \4x4 matrix [M] * [V] -> [V]
V; \column vector
Line 4,640 ⟶ 6,735:
N(3,C):= W(3,C);
];
];</langsyntaxhighlight>
 
=={{header|XSLT 1.0}}==
With input document ...
 
<langsyntaxhighlight lang="xml"><?xml-stylesheet href="matmul.templ.xsl" type="text/xsl"?>
<mult>
<A>
Line 4,657 ⟶ 6,752:
<r><c>4</c><c>5</c><c>6</c></r>
</B>
</mult></langsyntaxhighlight>
 
... and this referenced stylesheet ...
 
<langsyntaxhighlight lang="xml"><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
Line 4,737 ⟶ 6,832:
</xsl:template>
 
</xsl:stylesheet></langsyntaxhighlight>
{{out}} (in a browser):
Line 4,752 ⟶ 6,847:
 
A slightly smaller version of above stylesheet making use of (Non-"XSLT 1.0") EXSLT functions can be founde here: [[https://www.ibm.com/developerworks/mydeveloperworks/blogs/HermannSW/entry/matrix_multiplication30]]
 
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">dim a(4, 2)
a(0, 0) = 1 : a(0, 1) = 2
a(1, 0) = 3 : a(1, 1) = 4
a(2, 0) = 5 : a(2, 1) = 6
a(3, 0) = 7 : a(3, 1) = 8
dim b(2, 3)
b(0, 0) = 1 : b(0, 1) = 2 : b(0, 2) = 3
b(1, 0) = 4 : b(1, 1) = 5 : b(1, 2) = 6
dim prod(arraysize(a(),1), arraysize(b(),2))
 
if (arraysize(a(),2) = arraysize(b(),1)) then
for i = 0 to arraysize(a(),1)
for j = 0 to arraysize(b(),2)
for k = 0 to arraysize(a(),2)
prod(i, j) = prod(i, j) + (a(i, k) * b(k, j))
next k
next j
next i
 
for i = 0 to arraysize(prod(),1)-1
for j = 0 to arraysize(prod(),2)-1
print prod(i, j),
next j
print
next i
else
print "invalid dimensions"
end if
end</syntaxhighlight>
 
 
=={{header|zkl}}==
Using the GNU Scientific Library:
<langsyntaxhighlight 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);
B:=GSL.Matrix(2,3).set(1,2,3, 4,5,6);
(A*B).format().println(); // creates a new matrix</langsyntaxhighlight>
{{out}}
<pre>
Line 4,768 ⟶ 6,896:
Or, using lists:
{{trans|BASIC}}
<langsyntaxhighlight lang="zkl">fcn matMult(a,b){
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
foreach i,j,k in (m,p,n){ ans[i][j]+=a[i][k]*b[k][j]; }
ans
}</langsyntaxhighlight>
<langsyntaxhighlight 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) );
printM(matMult(a,b));
 
fcn printM(m){ m.pump(Console.println,rowFmt) }
fcn rowFmt(row){ ("%4d "*row.len()).fmt(row.xplode()) }</langsyntaxhighlight>
{{out}}
<pre>
Line 4,789 ⟶ 6,917:
 
=={{header|zonnon}}==
<langsyntaxhighlight lang="zonnon">
module MatrixOps;
type
Line 4,819 ⟶ 6,947:
Multiplication;
end MatrixOps.
</syntaxhighlight>
</lang>
 
=={{header|ZPL}}==
<syntaxhighlight lang="zpl">
<lang ZPL>
program matmultSUMMA;
 
Line 4,964 ⟶ 7,092:
return retval;
end;
</syntaxhighlight>
</lang>
2,054

edits