My resultant matrix seems to be undefined. At line 25, this is the error my chrome console gives: "Cannot set property "0" of undefined."
On looking at similar problems, most of the matrix multiplication solutions I've seen use 3 nested loops, as opposed to my 4. Those are probably the better way, but four loops is the only way that makes sense to me, since the iterations are over two separate rows and two separate columns. If this is the cause of my bug issue, could someone please explain why?
const A = [ [-4,0,5], [-3,-1,2], [6,7,-2], [1, 1, 2]],B = [ [1, 0, 3, 0], [4,5,-1, 2], [2, 4, 3, 1]],C = [];
for (var i = 0; i < A.length; i++) {
//C[i] = 0;
for (var j = 0; j < A[j].length; j++) {
//console.log(A[i][j]);
for (var y = 0; y < B[0].length; y++) {
C[i][y] = 0;
for (var x = 0; x < B.length; x++) {
//console.log(B[x][y]+ "["+x+","+y+"]");
console.log(C[i][y] + "[" + i + "," + y);
C[i][y] += A[i][j] * B[x][y];
}
console.log(C[i][y] + "[" + i + "," + y + "] is the resultant matrix");
}
}
}
Change //C[i] = 0;
to C[i] = [];
. You need to initialize array under C[i]
to access it later C[i][y] = 0;
const A = [ [-4,0,5], [-3,-1,2], [6,7,-2], [1, 1, 2]],B = [ [1, 0, 3, 0], [4,5,-1, 2], [2, 4, 3, 1]],C = [];
for (var i = 0; i < A.length; i++) {
C[i] = [];
for (var j = 0; j < A[j].length; j++) {
for (var y = 0; y < B[0].length; y++) {
C[i][y] = 0;
for (var x = 0; x < B.length; x++) {
C[i][y] += A[i][j] * B[x][y];
}
}
}
}
console.log(C);