Matrix multiplication: Difference between revisions

Content added Content deleted
m (→‎{{header|Ruby}}: Remove phantom category 'matrix.rb'.)
(Added second D version)
Line 825: Line 825:
[-17, -20, 25],
[-17, -20, 25],
[-21, -18, 33]]</pre>
[-21, -18, 33]]</pre>
===Alternative version===
All array sizes are verified at compile-time (and no matrix is copied), same output:
<lang d>import std.stdio, std.string, std.conv, std.numeric,
std.array, std.algorithm, std.traits;

template TMMul(M1, M2) { // helper
alias Unqual!(typeof(M1[0][0]))[M2[0].length][M1.length] TMMul;
}

void matrixMul(T, T2, size_t k, size_t m, size_t n)
(const ref T[m][k] A, const ref T[n][m] B,
/*out*/ ref T2[n][k] result) pure nothrow
if (is(T2 == Unqual!T)) {
T2[m] aux;
foreach (j; 0 .. n) {
foreach (k, row; B)
aux[k] = row[j];
foreach (i, ai; A)
result[i][j] = dotProduct(ai, aux);
}
}

string prettyPrint(T, size_t m, size_t n)(const ref T[m][n] M) {
return "[" ~ array(map!text(M[])).join(",\n ") ~ "]";
}

void main() {
const int[2][3] a = [[1, 2], [3, 4], [3, 6]];
const int[3][2] b = [[-3, -8, 3,], [-2, 1, 4]];

writeln("A =\n", prettyPrint(a), "\n");
writeln("B =\n", prettyPrint(b), "\n");
TMMul!(typeof(a), typeof(b)) result; // = void;
matrixMul(a, b, result);
writeln("A * B =\n", prettyPrint(result));
}</lang>


=={{header|ELLA}}==
=={{header|ELLA}}==