JavaScript - Multiplying Two Matrices

function Multiply_Matrices(A, B) {

    // Initialize the result matrix with zeros

    let C = [

        [0, 0, 0],

        [0, 0, 0],

        [0, 0, 0]

    ];

    // Perform matrix multiplication

    for (let i = 0; i < 3; i++) { // Loop over each row of A

        for (let j = 0; j < 3; j++) { // Loop over each column of B

            for (let k = 0; k < 3; k++) { // Loop over each element for dot product

                C[i][j] += A[i][k] * B[k][j];

            }

        }

    }

    return C;

}

// Example usage

let matrix_A = [

    [1, 2, 3],

    [4, 5, 6],

    [7, 8, 9]

];

let matrix_B = [

    [9, 8, 7],

    [6, 5, 4],

    [3, 2, 1]

];

let result = Multiply_Matrices(matrix_A, matrix_B);

console.log(result);

// Output: [[30, 24, 18], [84, 69, 54], [138, 114, 90]]

 

Explanation of the Code

Initialization: We create a result matrix C that is filled with zeros. This matrix will hold the results of the multiplication.

 

Matrix Multiplication Logic: We use three nested loops:

  • The outer loop cycles through each row of Matrix A.
  • The middle loop iterates across each column in Matrix B.
  • The inner loop computes the dot product of the appropriate row from Matrix A and column from Matrix B.

The product of each relevant element is added to the current position in the resulting matrix, C[i][j].