Matrix multiplication: Difference between revisions

Updated last D entry, + one more D entry (third)
(Updated second D entry)
(Updated last D entry, + one more D entry (third))
Line 955:
const Bt = B[0].length.iota.map!(i=> B.transversal(i).array).array;
return A.map!(a => Bt.map!(b => a.dotProduct(b)).array).array;
}
 
void main() {
immutable a = [[1, 2], [3, 4], [3, 6]];
immutable b = [[-3, -8, 3,], [-2, 1, 4]];
 
immutable form = "[%([%(%d, %)],\n %)]]";
writefln("A = \n" ~ form ~ "\n", a);
writefln("B = \n" ~ form ~ "\n", b);
writefln("A * B = \n" ~ form, matMul(a, b));
}</lang>
The output is the same.
 
===Pure Short Version===
<lang d>import std.stdio, std.range, std.numeric, std.algorithm;
 
T[][] matMul(T)(immutable T[][] A, immutable T[][] B) pure nothrow {
immutable Bt = B[0].length.iota.map!(i=> B.transversal(i).array)
.array;
return A.map!((immutable T[] a) => Bt.map!(b => a.dotProduct(b))
.array).array;
}
 
Line 970 ⟶ 991:
===Stronger Statically Typed Version===
All array sizes are verified at compile-time (and no matrix is copied). Same output.
<lang d>import std.stdio, std.string, std.convnumeric, std.numericalgorithm, std.array,traits;
std.algorithm, std.traits;
 
alias TMMul_helper(M1, M2) = Unqual!(ForeachType!(ForeachType!M1))
Line 982 ⟶ 1,002:
T2[m] aux;
foreach (immutable j; 0 .. n) {
foreach (immutable ki, const rowref bi; B)
aux[ki] = rowbi[j];
foreach (immutable i, const ref ai; A)
result[i][j] = dotProduct(ai, aux);
}