How to implement matrix multiplication in JavaScript

1 Answer

0 votes
// Multiply rows of A by columns of B.

// Print a 2D array (matrix)
function printMatrix(arr2d) {
  for (let i = 0; i < arr2d.length; i++) {
    let row = "";
    for (let j = 0; j < arr2d[i].length; j++) {
      row += arr2d[i][j].toString().padStart(4, " ");
    }
    console.log(row);
  }
}

// Multiply matrices A and B into C
function multipleMatrix(a, b, c) {
  for (let i = 0; i < c.length; i++) {
    for (let j = 0; j < c[i].length; j++) {
      for (let k = 0; k < a[i].length; k++) {
        c[i][j] += a[i][k] * b[k][j];
      }
    }
  }
}

// Create matrices
const a = [
  [1, 8, 5],
  [6, 7, 1],
  [8, 7, 6]
];

const b = [
  [4, 8, 1],
  [6, 5, 3],
  [4, 6, 5]
];

// Initialize result matrix C with zeros
const c = Array.from({ length: a.length }, () =>
  Array(b[0].length).fill(0)
);

// c[0, 0] = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]) + (a[0, 2] * b[2, 0])

printMatrix(a);
console.log();
printMatrix(b);
console.log();

multipleMatrix(a, b, c);

printMatrix(c);



/*
run:
        
   1   8   5
   6   7   1
   8   7   6

   4   8   1
   6   5   3
   4   6   5

  72  78  50
  70  89  32
  98 135  59
  
*/

 



answered 2 days ago by avibootz
...