Matrix multiplication: Difference between revisions

Added Easylang
(Applesoft BASIC)
(Added Easylang)
(14 intermediate revisions by 8 users not shown)
Line 10:
{{trans|Nim}}
 
<langsyntaxhighlight lang="11l">F matrix_mul(m1, m2)
assert(m1[0].len == m2.len)
V r = [[0.0] * m2[0].len] * m1.len
Line 43:
print(to_str(b))
print(to_str(matrix_mul(a, b)))
print(to_str(matrix_mul(b, a)))</langsyntaxhighlight>
 
{{out}}
Line 66:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Matrix multiplication 06/08/2015
MATRIXRC CSECT Matrix multiplication
USING MATRIXRC,R13
Line 171:
W DS CL16
YREGS
END MATRIXRC</langsyntaxhighlight>
{{out}}
<pre> 9 12 15
Line 180:
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
 
DEFINE PTR="CARD"
Line 259:
PutE() PrintE("equals") PutE()
PrintMatrix(res)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Matrix_multiplication.png Screenshot from Atari 8-bit computer]
Line 281:
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 311:
begin
Put (A * B);
end Matrix_Product;</langsyntaxhighlight>
{{out}}
<pre>
Line 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 345:
return Temp;
end "*";
end Matrix_Ops;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 353:
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
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 412:
exception index error:
putf(stand error, $x"Exception: index error."l$)
)</langsyntaxhighlight>
{{out}}
<pre>
Line 523:
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
main:
Line 531:
{first matrix,second matrix},mat mul, println
exit(0)
</syntaxhighlight>
</lang>
Alternatively, the follow code in macro-natural-Hopper:
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <natural.h>
#include <hopper.h>
Line 541:
now take 'first matrix', and take 'second matrix', and multiply it; then, print with a new line.
exit(0)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 563:
Matrix multiply in APL is just <tt>+.×</tt>. For example:
 
<langsyntaxhighlight 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)
Line 572:
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>
 
By contrast, A×B is for element-by-element multiplication of arrays of the same shape, and if they are simple elements, this is ordinary multiplication.
Line 588:
=={{header|AppleScript}}==
{{trans|JavaScript}}
<langsyntaxhighlight AppleScriptlang="applescript">--------------------- MATRIX MULTIPLY --------------------
 
-- matrixMultiply :: Num a => [[a]] -> [[a]] -> [[a]]
Line 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|Arturo}}==
 
<langsyntaxhighlight lang="rebol">printMatrix: function [m][
loop m 'row -> print map row 'val [pad to :string .format:".2f" val 6]
print "--------------------------------"
Line 784:
printMatrix B
printMatrix multiply A B
printMatrix multiply B A</langsyntaxhighlight>
 
{{out}}
Line 811:
=={{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 862:
}
}
}</langsyntaxhighlight>
===Using Objects===
<langsyntaxhighlight AutoHotkeylang="autohotkey">Multiply_Matrix(A,B){
if (A[1].Count() <> B.Count())
return ["Dimension Error"]
Line 878:
}
return R
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">A := [[1,2]
, [3,4]
, [5,6]
Line 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 905:
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk"># Usage: GAWK -f MATRIX_MULTIPLICATION.AWK filename
# Separate matrices a and b by a blank line
BEGIN {
Line 958:
function max(m, n) {
return m > n ? m : n
}</langsyntaxhighlight>
<p><b>Input:</b></p>
<pre>
Line 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 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]].
<langsyntaxhighlight 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)
Line 1,012:
10010 DATA1,2,3,4,5,6,7,8
20000 DATA2,3
20010 DATA1,2,3,4,5,6</langsyntaxhighlight>
 
===Full BASIC===
{{works with|Full BASIC}}
{{trans|BBC_BASIC}}
<langsyntaxhighlight lang="basic">DIM matrix1(4,2),matrix2(2,3)
 
MAT READ matrix1
Line 1,030:
 
MAT product=matrix1*matrix2
MAT PRINT product</langsyntaxhighlight>
{{out}}
<pre> 9 12 15
Line 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 1,059:
PRINT
NEXT
</syntaxhighlight>
</lang>
{{out}}
<pre> 9 12 15
Line 1,069:
<code>Mul</code> is a matrix multiplication idiom from [https://mlochbaum.github.io/bqncrate/ BQNcrate.]
 
<langsyntaxhighlight lang="bqn">Mul ← +˝∘×⎉1‿∞
 
(>⟨
Line 1,079:
⟨5, 6, 7, 8⟩
⟨9, 10, 11, 12⟩
⟩</langsyntaxhighlight><syntaxhighlight lang ="bqn">┌─
╵ 20 23 26 29
56 68 80 92
92 113 134 155
┘</langsyntaxhighlight>
[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 1,094:
29 40 51
39 54 69
</syntaxhighlight>
</lang>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
#define MAT_ELEM(rows,cols,r,c) (r*cols+c)
Line 1,160:
}
 
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
Line 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 1,209 ⟶ 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 1,216 ⟶ 1,311:
 
{{libheader|Blitz++}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <blitz/tinymat.h>
 
Line 1,236 ⟶ 1,331:
 
std::cout << C << std::endl;
}</langsyntaxhighlight>
{{out}}
(3,3):
Line 1,245 ⟶ 1,340:
===Generic solution===
main.cpp
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include "matrix.h"
Line 1,282 ⟶ 1,377:
 
} /* main() */
</syntaxhighlight>
</lang>
 
matrix.h
<langsyntaxhighlight lang="cpp">
#ifndef _MATRIX_H
#define _MATRIX_H
Line 1,463 ⟶ 1,558:
 
#endif /* _MATRIX_H */
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,472 ⟶ 1,567:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">alias Matrix => Integer[][];
 
void printMatrix(Matrix m) {
Line 1,536 ⟶ 1,631:
print("something went wrong!");
}
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 3]
Line 1,553 ⟶ 1,648:
 
Overload the '*' operator for arrays
<langsyntaxhighlight lang="chapel">proc *(a:[], b:[]) {
 
if (a.eltType != b.eltType) then
Line 1,573 ⟶ 1,668:
 
return c;
}</langsyntaxhighlight>
 
example usage (I could not figure out the syntax for multi-dimensional array literals)
<langsyntaxhighlight 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;
Line 1,600 ⟶ 1,695:
writeln(m5);
 
writeln(m4 * m5);</langsyntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">
(defn transpose
[s]
Line 1,621 ⟶ 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,630 ⟶ 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,638 ⟶ 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,660 ⟶ 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,682 ⟶ 1,777:
sum (* (aref a i j)
(aref b j k)))))
finally (return c)))</langsyntaxhighlight>
 
=={{header|D}}==
===Basic Version===
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.conv, std.numeric,
std.array, std.algorithm;
 
Line 1,719 ⟶ 1,814:
writefln("B = \n" ~ form ~ "\n", b);
writefln("A * B = \n" ~ form, matrixMul(a, b));
}</langsyntaxhighlight>
{{out}}
<pre>A =
Line 1,736 ⟶ 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,751 ⟶ 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,771 ⟶ 1,866:
writefln("B = \n" ~ form ~ "\n", b);
writefln("A * B = \n" ~ form, matMul(a, b));
}</langsyntaxhighlight>
The output is the same.
 
Line 1,777 ⟶ 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,809 ⟶ 1,904:
matrixMul(a, b, result);
writefln("A * B = \n" ~ form, result);
}</langsyntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Matrix_multiplication;
 
Line 1,905 ⟶ 2,000:
readln;
 
end.</langsyntaxhighlight>
{{out}}
<pre>a:
Line 1,921 ⟶ 2,016:
[75,00, 75,00, 75,00]
[117,00, 117,00, 117,00]]</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
proc matmul . m1[][] m2[][] r[][] .
r[][] = [ ]
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]
.
.
.
.
mat1[][] = [ [ 1 2 3 ] [ 4 5 6 ] ]
mat2[][] = [ [ 1 2 ] [ 3 4 ] [ 5 6 ] ]
matmul mat1[][] mat2[][] erg[][]
print erg[][]
</syntaxhighlight>
 
{{out}}
<pre>
[
[ 22 28 ]
[ 49 64 ]
]
</pre>
 
=={{header|EGL}}==
<syntaxhighlight lang="egl">
<lang EGL>
program Matrix_multiplication type BasicProgram {}
Line 1,957 ⟶ 2,080:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
 
<langsyntaxhighlight lang="ela">open list
 
mmult a b = [ [ sum $ zipWith (*) ar bc \\ bc <- (transpose b) ] \\ ar <- a ]
Line 1,967 ⟶ 2,090:
[[1, 2],
[3, 4]] `mmult` [[-3, -8, 3],
[-2, 1, 4]]</langsyntaxhighlight>
 
=={{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,984 ⟶ 2,107:
 
 
</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}}==
Line 1,990 ⟶ 2,133:
 
Code for matrix multiplication hardware design verification:
<langsyntaxhighlight lang="ella">MAC ZIP = ([INT n]TYPE t: vector1 vector2) -> [n][2]t:
[INT k = 1..n](vector1[k], vector2[k]).
Line 2,034 ⟶ 2,177:
).
 
COM test: just displaysignal MOC</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
 
%% Multiplies two matrices. Usage example:
Line 2,096 ⟶ 2,239:
multiply_row_by_col(Row, []) ->
[].
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,104 ⟶ 2,247:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM MAT_PROD
 
Line 2,142 ⟶ 2,285:
 
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}<pre>
9 12 15
Line 2,151 ⟶ 2,294:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function matrix_mul(sequence a, sequence b)
sequence c
if length(a[1]) != length(b) then
Line 2,166 ⟶ 2,309:
return c
end if
end function</langsyntaxhighlight>
 
=={{header|Excel}}==
Line 2,254 ⟶ 2,397:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
let MatrixMultiply (matrix1 : _[,] , matrix2 : _[,]) =
let result_row = (matrix1.GetLength 0)
Line 2,267 ⟶ 2,410:
ret
 
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
Line 2,280 ⟶ 2,423:
Using a list of lists representation. The multiplication is done using three nested loops.
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 2,312 ⟶ 2,455:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,320 ⟶ 2,463:
 
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">
Array a[3,2]
Array b[2,3]
Line 2,326 ⟶ 2,469:
[b]:=[(1,1,2,3,5,8)]
[a]*[b]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,337 ⟶ 2,480:
{{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 2,350 ⟶ 2,493:
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 2,378 ⟶ 2,521:
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 2,388 ⟶ 2,531:
print'(<n>f15.7)',transpose(matmul(a,b))
end program
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">type Matrix
dim as double m( any , any )
declare constructor ( )
Line 2,434 ⟶ 2,577:
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>
</lang>
 
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">matprod[a is array, b is array] :=
{
c = makeArray[[length[a], length[b@0]], 0]
Line 2,452 ⟶ 2,595:
 
return c
}</langsyntaxhighlight>
 
=={{header|Futhark}}==
Line 2,459 ⟶ 2,602:
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 2,485 ⟶ 2,628:
# [ 19, 26, 33 ],
# [ 29, 40, 51 ],
# [ 39, 54, 69 ] ]</langsyntaxhighlight>
 
 
=={{header|Generic}}==
<langsyntaxhighlight lang="cpp">
generic coordinaat
{
Line 3,159 ⟶ 3,302:
 
}
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
===Library gonum/mat===
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,185 ⟶ 3,328:
m.Mul(a, b)
fmt.Println(mat.Formatted(&m))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,193 ⟶ 3,336:
 
===Library go.matrix===
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,220 ⟶ 3,363:
}
fmt.Printf("Product of A and B:\n%v\n", p)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,237 ⟶ 3,380:
 
===2D representation===
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 3,296 ⟶ 3,439:
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 3,314 ⟶ 3,457:
</pre>
===Flat representation===
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 3,369 ⟶ 3,512:
}
p.print("Product of A and B:")
}</langsyntaxhighlight>
Output is similar to 2D version.
 
Line 3,375 ⟶ 3,518:
=== 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 3,391 ⟶ 3,534:
}
}
}</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 3,403 ⟶ 3,546:
}
}
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def m4by2 = [ [ 1, 2 ],
[ 3, 4 ],
[ 5, 6 ],
Line 3,416 ⟶ 3,559:
matmulWOIL(m4by2, m2by3).each { println it }
println()
matmulWOT(m4by2, m2by3).each { println it }</langsyntaxhighlight>
 
{{out}}
Line 3,433 ⟶ 3,576:
A somewhat inefficient version with lists (''transpose'' is expensive):
 
<langsyntaxhighlight Haskelllang="haskell">import Data.List
 
mmult :: Num a => [[a]] -> [[a]] -> [[a]]
Line 3,441 ⟶ 3,584:
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 3,457 ⟶ 3,600:
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===
<langsyntaxhighlight Haskelllang="haskell">multiply :: Num a => [[a]] -> [[a]] -> [[a]]
multiply us vs = map (mult [] vs) us
where
Line 3,476 ⟶ 3,619:
multiply
[[1, 2], [3, 4]]
[[-3, -8, 3], [-2, 1, 4]]</langsyntaxhighlight>
{{out}}
<pre>[-7,-6,11]
Line 3,482 ⟶ 3,625:
 
===With List and without transpose - shorter===
<langsyntaxhighlight Haskelllang="haskell">mult :: Num a => [[a]] -> [[a]] -> [[a]]
mult uss vss =
let go xs
Line 3,492 ⟶ 3,635:
main =
mapM_ print $
mult [[1, 2], [3, 4]] [[-3, -8, 3], [-2, 1, 4]]</langsyntaxhighlight>
{{out}}
<pre>[-7,-6,11]
Line 3,498 ⟶ 3,641:
 
===With Numeric.LinearAlgebra===
<langsyntaxhighlight Haskelllang="haskell">import Numeric.LinearAlgebra
 
a, b :: Matrix I
Line 3,506 ⟶ 3,649:
 
main :: IO ()
main = print $ a <> b</langsyntaxhighlight>
{{out}}
<pre>
Line 3,514 ⟶ 3,657:
 
=={{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 3,528 ⟶ 3,671:
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 3,539 ⟶ 3,682:
Using the provided matrix library:
 
<langsyntaxhighlight lang="icon">
link matrix
 
Line 3,553 ⟶ 3,696:
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 3,573 ⟶ 3,716:
return result
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,591 ⟶ 3,734:
=={{header|IDL}}==
 
<langsyntaxhighlight lang="idl">result = arr1 # arr2</langsyntaxhighlight>
 
=={{header|Idris}}==
<langsyntaxhighlight lang="idris">import Data.Vect
 
Matrix : Nat -> Nat -> Type -> Type
Line 3,607 ⟶ 3,750:
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 3,620 ⟶ 3,763:
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 3,634 ⟶ 3,777:
 
=={{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 3,652 ⟶ 3,795:
}
return ans;
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 3,660 ⟶ 3,803:
 
Extends [[Matrix Transpose#JavaScript]]
<langsyntaxhighlight lang="javascript">// returns a new matrix
Matrix.prototype.mult = function(other) {
if (this.width != other.height) {
Line 3,682 ⟶ 3,825:
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 3,688 ⟶ 3,831:
 
====Functional====
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 3,754 ⟶ 3,897:
}
 
})();</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";
 
Line 3,850 ⟶ 3,993:
// MAIN ---
return main();
}))();</langsyntaxhighlight>
{{Out}}
<pre>[[51,-8,26,-18],[-8,-38,-6,34],[33,42,38,-14],[17,74,72,44]]</pre>
Line 3,858 ⟶ 4,001:
 
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 3,875 ⟶ 4,018:
| 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 3,887 ⟶ 4,030:
Uses module listed in [[Matrix Transpose#Jsish]]
 
<langsyntaxhighlight lang="javascript">/* Matrix multiplication, in Jsish */
require('Matrix');
 
Line 3,904 ⟶ 4,047:
a.mult(b) ==> { height:2, mtx:[ [ -7, -6, 11 ], [ -17, -20, 25 ] ], width:3 }
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 3,912 ⟶ 4,055:
=={{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 3,920 ⟶ 4,063:
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 3,973 ⟶ 4,116:
)
printMatrix(m1 * m2)
}</langsyntaxhighlight>
 
{{out}}
Line 3,985 ⟶ 4,128:
=={{header|Lambdatalk}}==
 
<langsyntaxhighlight lang="scheme">
{require lib_matrix}
 
Line 4,008 ⟶ 4,151:
[ 66, 81,-12],
[-24,-18,150]]
</syntaxhighlight>
</lang>
 
=={{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 4,023 ⟶ 4,166:
Use the LFE <code>transpose/1</code> function from [[Matrix transposition]].
 
<langsyntaxhighlight lang="lisp">
(defun matrix* (matrix-1 matrix-2)
(list-comp
Line 4,031 ⟶ 4,174:
(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 4,045 ⟶ 4,188:
> (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 4,060 ⟶ 4,203:
MatrixP$ =MatrixMultiply$( MatrixA$, MatrixB$)
call DisplayMatrix MatrixP$
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,082 ⟶ 4,225:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">TO LISTVMD :A :F :C :NV
;PROCEDURE LISTVMD
;A = LIST
Line 4,186 ⟶ 4,329:
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 4,219 ⟶ 4,362:
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
Line 4,233 ⟶ 4,376:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckMatMult {
\\ Matrix Multiplication
Line 4,301 ⟶ 4,444:
}
CheckMatMult2
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,312 ⟶ 4,455:
 
=={{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 4,333 ⟶ 4,476:
 
=={{header|MathCortex}}==
<langsyntaxhighlight lang="mathcortex">
>> A = [2,3; -2,1]
2 3
Line 4,345 ⟶ 4,488:
14 10
2 -2
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Line 4,353 ⟶ 4,496:
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 4,380 ⟶ 4,523:
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 4,415 ⟶ 4,558:
 
19 22
43 50</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">a: matrix([1, 2],
[3, 4],
[5, 6],
Line 4,430 ⟶ 4,573:
[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 4,444 ⟶ 4,587:
=1.3e-15 1. -4.4e-16 -3.3e-16
=0. 0. 1. 4.4e-16
=0. 0. 0. 1.</langsyntaxhighlight>
 
=={{header|Nim}}==
{{libheader|strfmt}}
<langsyntaxhighlight lang="nim">import strfmt
 
type Matrix[M, N: static[int]] = array[M, array[N, float]]
Line 4,478 ⟶ 4,621:
echo b
echo a * b
echo b * a</langsyntaxhighlight>
 
{{out}}
Line 4,501 ⟶ 4,644:
 
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 4,513 ⟶ 4,656:
done
done;
z</langsyntaxhighlight>
 
# matrix_multiply [|[|1;2|];[|3;4|]|] [|[|-3;-8;3|];[|-2;1;4|]|];;
Line 4,520 ⟶ 4,663:
{{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 4,536 ⟶ 4,679:
(List.map2 ( * ) row column))
m2)
m1</langsyntaxhighlight>
 
# matrix_multiply [[1;2];[3;4]] [[-3;-8;3];[-2;1;4]];;
Line 4,542 ⟶ 4,685:
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">a = zeros(4);
% prepare the matrix
% 1 1 1 1
Line 4,554 ⟶ 4,697:
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.
<langsyntaxhighlight lang="scheme">; short version based on 'apply'
(define (matrix-multiply matrix1 matrix2)
(map
Line 4,567 ⟶ 4,710:
matrix2))
matrix1))
</syntaxhighlight>
</lang>
 
> (matrix-multiply '((1 2) (3 4)) '((-3 -8 3) (-2 1 4)))
Line 4,573 ⟶ 4,716:
 
This long version works on lists of lists with any matrix dimensions.
<langsyntaxhighlight lang="scheme">; long version based on recursive cycles
(define (matrix-multiply A B)
(define m (length A))
Line 4,601 ⟶ 4,744:
r))))
rows)))))
</syntaxhighlight>
</lang>
 
Testing large matrices:
<langsyntaxhighlight lang="scheme">; [372x17] * [17x372]
(define M 372)
(define N 17)
Line 4,627 ⟶ 4,770:
 
(for-each print (matrix-multiply A B))
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 4,648 ⟶ 4,791:
(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
Line 4,680 ⟶ 4,961:
next
end function
</syntaxhighlight>
</lang>
 
When using matrices in Video graphics, speed is important. Here is a matrix multiplier written in OxygenBasics's x86 Assembly code.
<langsyntaxhighlight lang="oxygenbasic">
'Example of matrix layout mapped to an array of 4x4 cells
'
Line 4,797 ⟶ 5,078:
 
Print ShowMatrix C,n
</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<syntaxhighlight lang ="parigp">M*N</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 4,807 ⟶ 5,088:
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 4,841 ⟶ 5,122:
 
$c = mmult(\@a,\@b);
display($c)</langsyntaxhighlight>
{{out}}
<pre> -7 -6 11
Line 4,847 ⟶ 5,128:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">matrix_mul</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
Line 4,907 ⟶ 5,188:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,934 ⟶ 5,215:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de matMul (Mat1 Mat2)
(mapcar
'((Row)
Line 4,943 ⟶ 5,224:
(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 4,972 ⟶ 5,253:
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 4,998 ⟶ 5,279:
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)
Line 5,035 ⟶ 5,316:
"`$a * `$c ="
show (multarrays $a $c)
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 5,062 ⟶ 5,343:
{{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 5,072 ⟶ 5,353:
% 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 5,098 ⟶ 5,379:
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 5,153 ⟶ 5,434:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>matrix a: (2, 3)
Line 5,169 ⟶ 5,450:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">a=((1, 1, 1, 1), # matrix A #
(2, 4, 8, 16),
(3, 9, 27, 81),
Line 5,206 ⟶ 5,487:
print '%8.2f '%val,
print ']'
print ')'</langsyntaxhighlight>
 
Another one, {{trans|Scheme}}
<langsyntaxhighlight lang="python">from operator import mul
 
def matrixMul(m1, m2):
Line 5,218 ⟶ 5,499:
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 5,245 ⟶ 5,526:
(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}}==
Line 5,275 ⟶ 5,556:
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" perl6line>sub mmult(@a,@b) {
my @p;
for ^@a X ^@b[0] -> ($r, $c) {
Line 5,293 ⟶ 5,574:
[ -1/6, 1/4, -1/6, 1/24];
 
.say for mmult(@a,@b);</langsyntaxhighlight>
 
{{out}}
Line 5,307 ⟶ 5,588:
Some people will find this more readable and elegant, and others will, well, not.
 
<syntaxhighlight lang="raku" perl6line>sub mmult(\a,\b) {
[
for ^a -> \r {
Line 5,317 ⟶ 5,598:
}
]
}</langsyntaxhighlight>
 
Here we use Z with an "op" of <tt>*</tt>, which is a zip with multiply. This, along with the <tt>[+]</tt> reduction operator, replaces the inner loop. We chose to split the outer X loop back into two loops to make it convenient to collect each subarray value in <tt>[...]</tt>. It just collects all the returned values from the inner loop and makes an array of them. The outer loop simply returns the outer array.
Line 5,323 ⟶ 5,604:
For conciseness, the above could be written as:
 
<syntaxhighlight lang="raku" perl6line>multi infix:<×> (@A, @B) {
@A.map: -> @a { do [+] @a Z× @B[*;$_] for ^@B[0] }
}</langsyntaxhighlight>
 
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 5,350 ⟶ 5,639:
<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 x.3=4 5 6 7 8 /*║ a sign, quotesdefine aren'tA needed.matrix size and elements */
bmat=2X3 1 2 3 4 5 6 /* " B " x.4= 7 8 " " " /*╚═══════════════════════════════════╝*/
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\==''; parseB 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 y.=; /* multiply A x B 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*/
w= 0 /*W is max width of an matrix element.*/
Parse Var size rows 'X' cols
c.= 0; 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; w= max(w, length(c.i.j) )
n=0
end /*k*/ /* ↑ */
Do r=1 To rows
end /*j*/ /* └────────◄───────────┐ */
Do c=1 To cols
end /*i*/ /*max width of the matrix elements─►─┘ */
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 showMat 'A', Arows, Acols /*display matrix A ───► the terminal.*/
Say 'Syntax raised in line' sigl
call showMat 'B', Brows, Bcols /* " " B ───► " " */
Say sourceline(sigl)
call showMat '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>
showMat: parse arg mat,rows,cols; say; say center(mat 'matrix', cols*(w+1) + 9, "─")
do r=1 for rows; _= ' '
do c=1 for cols; _= _ right( value(mat'.'r"."c), w); end; say _
end /*r*/; return</lang>
{{out|output|text=&nbsp; when using the internal default input:}}
<pre>
------- matrix A -------
───A matrix────
1 2 +-----+
3 4 | 1 2 |
5 6 | 3 4 |
7 8 | 5 6 |
| 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 +----------+
19 26 33 | 9 12 15 |
29 40 51 | 19 26 33 |
39 54 69 | 29 40 51 |
| 39 54 69 |
+----------+
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
n = 3
Line 5,426 ⟶ 5,769:
see nl
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,432 ⟶ 5,775:
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 { |bc| ar.zip(bc).map{ |x| x.inject(&:*) }.sum }
end
end</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
struct Matrix {
dat: [[f32; 3]; 3]
Line 5,512 ⟶ 5,864:
}
 
</syntaxhighlight>
</lang>
 
=={{header|S-lang}}==
<langsyntaxhighlight Clang="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
Line 5,530 ⟶ 5,882:
reshape(B, [2,3]);
printf("\nA * B is %S (with reshaped B to match A)\n", A*B);
print(A*B);</langsyntaxhighlight>
 
{{out}}
Line 5,555 ⟶ 5,907:
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 5,570 ⟶ 5,922:
yield for(col <- b.transpose)
yield row zip col map Function.tupled(_*_) reduceLeft (_+_)
}</langsyntaxhighlight>
 
Examples:
Line 5,600 ⟶ 5,952:
{{trans|Common Lisp}}
This version works on lists of lists:
<langsyntaxhighlight lang="scheme">(define (matrix-multiply matrix1 matrix2)
(map
(lambda (row)
Line 5,607 ⟶ 5,959:
(apply + (map * row column)))
matrix2))
matrix1))</langsyntaxhighlight>
 
> (matrix-multiply '((1 2) (3 4)) '((-3 -8 3) (-2 1 4)))
Line 5,613 ⟶ 5,965:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const type: matrix is array array float;
 
const func matrix: (in matrix: left) * (in matrix: right) is func
Line 5,638 ⟶ 5,990:
end for;
end if;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#mmult]
Line 5,649 ⟶ 6,001:
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 5,660 ⟶ 6,012:
[-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 5,693 ⟶ 6,045:
for line in matrix_multi(a, b) {
say line.map{|i|'%3d' % i }.join(', ')
}</langsyntaxhighlight>
{{out}}
<pre> 9, 12, 15
Line 5,704 ⟶ 6,056:
{{works with|OpenAxiom}}
{{works with|Axiom}}
<langsyntaxhighlight SPADlang="spad">(1) -> A:=matrix [[1,2],[3,4],[5,6],[7,8]]
 
+1 2+
Line 5,729 ⟶ 6,081:
| |
+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 5,753 ⟶ 6,105:
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 IMatrix = struct
fun dot(x,y) = Vector.foldli (fn (i,xi,agg) => agg+xi*Vector.sub(y,i)) 0 x
fun x*y =
Line 5,779 ⟶ 6,131:
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 5,793 ⟶ 6,145:
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 5,802 ⟶ 6,154:
1 | 3 1 3 5 |
2 | 9 4 6 11 |
+---------------------+</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">@inlinable
public func matrixMult<T: Numeric>(_ m1: [[T]], _ m2: [[T]]) -> [[T]] {
let n = m1[0].count
Line 5,864 ⟶ 6,216:
let m3 = matrixMult(m1, m2)
 
printMatrix(m3)</langsyntaxhighlight>
 
{{out}}
Line 5,872 ⟶ 6,224:
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
operator (A matmul B)
$A -> \[i](
Line 5,907 ⟶ 6,259:
' -> !OUT::write
($a matmul $b) -> printMatrix&{w:2} -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,926 ⟶ 6,278:
=={{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 5,945 ⟶ 6,297:
}
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 5,953 ⟶ 6,305:
=={{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 5,967 ⟶ 6,319:
{{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}}==
<langsyntaxhighlight lang="scheme">#lang transd
 
 
Line 5,996 ⟶ 6,348:
(lout C))
)
}</langsyntaxhighlight>{{out}}
<pre>
[[50, 40, 30, 20, 10],
Line 6,006 ⟶ 6,358:
 
=={{header|UNIX Shell}}==
<langsyntaxhighlight lang="bash">
#!/bin/bash
 
Line 6,190 ⟶ 6,542:
echo
echo
</syntaxhighlight>
</lang>
 
=={{header|Ursala}}==
Line 6,198 ⟶ 6,550:
the built in rational number type.
 
<langsyntaxhighlight Ursalalang="ursala">#import rat
 
a =
Line 6,220 ⟶ 6,572:
#cast %qLL
 
test = mmult(a,b)</langsyntaxhighlight>
{{out}}
<pre><
Line 6,230 ⟶ 6,582:
=={{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 6,255 ⟶ 6,607:
Next
End Sub
</syntaxhighlight>
</lang>
 
{{Out}}
Line 6,265 ⟶ 6,617:
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang="vfp">
LOCAL ARRAY a[4,2], b[2,3], c[4,3]
CLOSE DATABASES ALL
Line 6,308 ⟶ 6,660:
ENDIF
ENDPROC
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
{{libheader|Wren-matrix}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./matrix" for Matrix
import "./fmt" for Fmt
 
var a = Matrix.new([
Line 6,333 ⟶ 6,685:
Fmt.mprint(b, 2, 0)
System.print("\nMatrix A x B:\n")
Fmt.mprint(a * b, 3, 0)</langsyntaxhighlight>
 
{{out}}
Line 6,358 ⟶ 6,710:
 
=={{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 6,384 ⟶ 6,736:
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 6,401 ⟶ 6,753:
<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 6,481 ⟶ 6,833:
</xsl:template>
 
</xsl:stylesheet></langsyntaxhighlight>
{{out}} (in a browser):
Line 6,499 ⟶ 6,851:
 
=={{header|Yabasic}}==
<langsyntaxhighlight lang="yabasic">dim a(4, 2)
a(0, 0) = 1 : a(0, 1) = 2
a(1, 0) = 3 : a(1, 1) = 4
Line 6,527 ⟶ 6,879:
print "invalid dimensions"
end if
end</langsyntaxhighlight>
 
 
=={{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 6,545 ⟶ 6,897:
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 6,566 ⟶ 6,918:
 
=={{header|zonnon}}==
<langsyntaxhighlight lang="zonnon">
module MatrixOps;
type
Line 6,596 ⟶ 6,948:
Multiplication;
end MatrixOps.
</syntaxhighlight>
</lang>
 
=={{header|ZPL}}==
<syntaxhighlight lang="zpl">
<lang ZPL>
program matmultSUMMA;
 
Line 6,741 ⟶ 7,093:
return retval;
end;
</syntaxhighlight>
</lang>
1,969

edits