While my code is running without error, my resultant matrix (ie. C) is incorrect. What C should be:[6, 20, 3, 5],[-3, 3,-2, 0],[30, 27, 5, 12],[9, 13, 8, 4].
What C currently is, based on my code:[35,45,25,15],[14,18,10,6],[-14,-18,-10,-6],[14,18,10,6]
I have a feeling this is from mismatching my loops for my resultant matrix, but I can't seem to figure out the issue.
I've also noticed that other matrix multiplication threads on this forum use 3 loops, as opposed to my 4 loops. If this is the reason for my error, could you please explain why? Shouldn't there be an iteration for the 2 separate rows and 2 separate columns?
const A = [ [-4,0,5],
[-3,-1,2],
[6,7,-2],
[1, 1, 2]
];
const 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++){
//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");
}
}
}
console.log(JSON.stringify(C)); //to print out resultant matrix in array format