Matrix multiplication: Difference between revisions

Added Easylang
(→‎{{header|Raku}}: add an other take)
(Added Easylang)
(10 intermediate revisions by 6 users not shown)
Line 1,165:
 
This code should work with any version of the .NET Framework and C# language
 
==={{header|Class}}===
 
<syntaxhighlight lang="csharp">public class Matrix
Line 1,210 ⟶ 1,212:
}
}</syntaxhighlight>
 
==={{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,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">
Line 1,985 ⟶ 2,108:
 
</syntaxhighlight>
 
=={{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 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}}==
Line 5,331 ⟶ 5,612:
{{works with|Rakudo|2022.07-3}}
 
Here is an evena more concisefunctional 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,^a Z* @B)^b {}
sub crossinfix:<×>(@A, ([Z] @B), with{ =>(@A { [+Z] @^a Z* B).rotor(@^bB) })
</syntaxhighlight>
.rotor(@B);
}</syntaxhighlight>
 
=={{header|Rascal}}==
Line 5,362 ⟶ 5,642:
 
=={{header|REXX}}==
<syntaxhighlight 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</syntaxhighlight>
{{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>
 
Line 5,441 ⟶ 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>
 
Line 6,322 ⟶ 6,665:
{{libheader|Wren-matrix}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">import "./matrix" for Matrix
import "./fmt" for Fmt
 
var a = Matrix.new([
1,969

edits