[英]Can not seem to figure out why my matrix multiplication function is not working
let multiply = function(a, b) {
let c = [];
for(let row = 0; row < 4; row++){
for(let col = 0; col < 4;col++){
for(let i = 0; i < 4; i++){
c[col + (4*row)] += a[i][row] * b[col][i];
}
}
}
The function takes two four by four matrixes and outputs an array of length 16. It does not seem to be giving me the correct array.该函数采用两个四乘四矩阵并输出一个长度为 16 的数组。它似乎没有给我正确的数组。
This should do the trick这应该可以解决问题
let multiply = function(a, b) {
let c = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
for(let row = 0; row < 4; row++){
for(let col = 0; col < 4; col++){
for(let i = 0; i < 4; i++){
c[col + (4*row)] += a[row][i] * b[i][col];
}
}
}
return c;
}
Notice that you need to initialize the output array and your row x col
multiplication was wrong;请注意,您需要初始化输出数组,并且您的
row x col
乘法是错误的; you need:你需要:
a[row][i] * b[i][col]
instead of代替
a[i][row] * b[col][i]
The function should also return the resulting array.该函数还应返回结果数组。
You can give it a try using JSFiddle: https://jsfiddle.net/1fxLpucg/您可以尝试使用 JSFiddle: https ://jsfiddle.net/1fxLpucg/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.