Matrix multiplication: Difference between revisions

Content added Content deleted
m (→‎{{header|REXX}}: added REXX language.)
Line 714: Line 714:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio: writefln;
<lang d>import std.stdio, std.string;
import std.string: format, join;


T[][] matrixMul(T)(T[][] m1, T[][] m2) {
pure bool isRectangular(T)(const T[][] matrix) {
bool isRectangular(T[][] matrix) {
foreach (row; matrix)
foreach (row; matrix)
if (row.length != matrix[0].length)
if (row.length != matrix[0].length)
return false;
return false;
return true;
}
return true;
}

T[][] result;
if (isRectangular(m1) && isRectangular(m2) && m1[0].length == m2.length) {
result = new T[][](m1.length, m2[0].length);


T[][] matrixMul(T)(T[][] m1, T[][] m2)
in {
assert(isRectangular(m1) && isRectangular(m2) &&
m1[0].length == m2.length);
} body {
auto result = new T[][](m1.length, m2[0].length);
foreach (i, m1_row_i; m1)
foreach (i, m1_row_i; m1)
for (int j; j < m2[0].length; j++) {
foreach (j; 0 .. m2[0].length) {
T aux = 0;
T aux = 0;
foreach (k, m2_row_k; m2)
foreach (k, m2_row_k; m2)
Line 736: Line 736:
result[i][j] = aux;
result[i][j] = aux;
}
}
} else
return result;
}
throw new Exception("matrixMul Error");
return result;
}


string prettyPrint(T)(T[][] matrix) {
string prettyPrint(T)(T[][] matrix) {
Line 749: Line 747:


void main() {
void main() {
float[][] a = [[1, 2], [3, 4], [3, 6]];
enum a = [[1, 2], [3, 4], [3, 6]];
float[][] b = [[-3, -8, 3,], [-2, 1, 4]];
enum b = [[-3, -8, 3,], [-2, 1, 4]];
writeln("A = \n", prettyPrint(a));

writefln("A = \n", prettyPrint(a));
writeln("\nB = \n", prettyPrint(b));
writefln("\nB = \n", prettyPrint(b));
writeln("\nA * B = \n", prettyPrint(matrixMul(a, b)));
writefln("\nA * B = \n", prettyPrint(matrixMul(a, b)));
}</lang>
}</lang>
Output:
<pre>A =
[[1,2],
[3,4],
[3,6]]

B =
[[-3,-8,3],
[-2,1,4]]

A * B =
[[-7,-6,11],
[-17,-20,25],
[-21,-18,33]]</pre>

=={{header|ELLA}}==
=={{header|ELLA}}==
Sample originally from ftp://ftp.dra.hmg.gb/pub/ella (a now dead link) - Public release.
Sample originally from ftp://ftp.dra.hmg.gb/pub/ella (a now dead link) - Public release.