Matrix multiplication: Difference between revisions

Updated D code
(Add a C# matrix class with multiply operator)
(Updated D code)
Line 776:
 
=={{header|D}}==
<lang d>import std.stdio, std.string, std.conv, std.numeric;,
std.array, std.algorithm;
 
pure bool isRectangular(T)(const T[][] matrixM) {
return !canFind!((r){ return r.length != M[0].length; })(M);
foreach (row; matrix)
if (row.length != matrix[0].length)
return false;
return true;
}
 
T[][] matrixMul(T)(const T[][] aA, const T[][] bB)
in {
assert(isRectangular(aA) && isRectangular(bB) &&
aA[0].length == bB.length);
} body {
auto result = new T[][](aA.length, bB[0].length);
auto aux = new T[bB.length];
foreach (j; 0 .. bB[0].length) {
foreach (k, row; 0 .. b.lengthB)
aux[k] = b[k]row[j];
foreach (i, ai; 0 .. a.lengthA)
result[i][j] = dotProduct(a[i]ai, aux);
}
return result;
}
return falseresult;
}
 
string prettyPrint(T)(constin T[][] matrixM) {
return "[" ~ resultarray(map!text(M)).join(",\n ") ~ "]";
string[] result;
foreach (row; matrix)
result ~= text(row);
return "[" ~ result.join(",\n ") ~ "]";
}
 
Line 812 ⟶ 807:
enum b = [[-3, -8, 3,], [-2, 1, 4]];
 
writeln("A = \n", prettyPrint(a), "\n");
writeln("\nBB = \n", prettyPrint(b), "\n");
writeln("\nAA * B = \n", prettyPrint(matrixMul(a, b)));
}</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],
Anonymous user