1

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
S K
  • 19
  • 6

1 Answers1

1

You don't need to use four loops. You need only three loops that is the problem. The no of nested loops to use for a problem are not your choice.

This problem needs only three nested loops. To multiply matrices. We multiple each element of each row of the first matrix with corresponding element of each column of second matrix.

Now the thing which you need to understand is that the third nested loop will generate -4,0,5. At this point we don't need another loop because we add them to corresponding value. Not each value is added to all.

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]
         ];
const C = [];

for(let i = 0; i < A.length; i++){
  C[i] = []
  for(let j = 0; j < B[0].length; j++){
    C[i][j] = 0
    for(let k = 0; k < A[0].length; k++){    
      C[i][j] += A[i][k] * B[k][j];
    }  
  }
  
}
//[6, 20, 3, 5],[-3, 3,-2, 0],[30, 27, 5, 12],[9, 13, 8, 4]
console.log(C);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73