Skip to main content

Multiply two matrices in javascript

ES6 Solution to multiplying two matrices. O(n^3)

Run the code here: https://repl.it/@VinitKhandelwal/multiply-two-matrices-javascript

Solution

const multiply = (a, b) => {
  const aRows = a.length;
  const aCols = a[0].length;
  const bRows = b.length;
  const bCols = b[0].length;
  const ans = new Array(aRows);  // initialize array of rows
  for (let i = 0; i < aRows; i++) {
    ans[i] = new Array(bCols); // initialize the current row
    for (let j = 0; j < bCols; j++) {
      ans[i][j] = 0;             // initialize the current cell
      for (let k = 0; k < aCols; k++) {
        ans[i][j] += a[i][k] * b[k][j];
      }
    }
  }
  return ans;
}

const display = m => {
  for (var r = 0; r < m.length; ++r) {
    console.log('  ' + m[r].join(' '));
  }
}

Test Input

display([[8, 3], [2, 4], [3, 6]]);
display([[1, 2, 3], [4, 6, 8]]);
display(multiply([[8, 3], [2, 4], [3, 6]], [[1, 2, 3], [4, 6, 8]]));

Output

8 3
2 4
3 6
1 2 3
4 6 8
20 34 48
18 28 38
27 42 57

Comments