所以我有这个乘法矩阵的代码,但它只适用于2x2矩阵。我没有那种编程经验,所以我不知道我做错了什么。谁能告诉我这个代码如何用于乘以3x3矩阵?我如何管理结果写成矩阵而不只是一行?有没有比document.write(mResult)更好的方法;?
function multiply(m1, m2) {
var result = [];
for (var i = 0; i < m1.length; i++) {
result[i] = [];
for (var j = 0; j < m2[0].length; j++) {
var sum = 0;
for (var k = 0; k < m1[0].length; k++) {
sum += m1[i][k] * m2[k][j];
}
result[i][j] = sum;
}
}
return result;
}
var m1 = [
[1, 2],
[3, 8]
];
var m2 = [
[5, 9],
[7, 1]
];
var mResult = multiply(m1, m2);
document.write(mResult);
&#13;
答案 0 :(得分:0)
这应该有效:
function multiply (a, b) {
const transpose = (a) => a[0].map((x, i) => a.map((y) => y[i]));
const dotproduct = (a, b) => a.map((x, i) => a[i] * b[i]).reduce((m, n) => m + n);
const result = (a, b) => a.map((x) => transpose(b).map((y) => dotproduct(x, y)));
return result(a, b);
}