0

So I have this code for multiplying matrices but it only works for 2x2 matrices. I'm not that experienced in programming so I have no idea what I am doing wrong. Can anyone tell me how this code is working for multiplying 3x3 matrices? And how can I manage that the result is written like a matrix and not just in one line? Is there a better way than document.write(mResult);?

function multiply(m1, m2) {
  var result = [];
  for (var i = 0; i < m1.length; i++) {
    result[i] = [];
    for (var j = 0; j < m2[0].length; j++) {
      var sum = 0;
      for (var k = 0; k < m1[0].length; k++) {
        sum += m1[i][k] * m2[k][j];
      }
      result[i][j] = sum;
    }
  }
  return result;
}

var m1 = [
  [1, 2],
  [3, 8]
];
var m2 = [
  [5, 9],
  [7, 1]
];
var mResult = multiply(m1, m2);
document.write(mResult);
chazsolo
  • 7,873
  • 1
  • 20
  • 44

1 Answers1

0

This should work:

function multiply (a, b) {
  const transpose = (a) => a[0].map((x, i) => a.map((y) => y[i]));
  const dotproduct = (a, b) => a.map((x, i) => a[i] * b[i]).reduce((m, n) => m + n);
  const result = (a, b) => a.map((x) => transpose(b).map((y) => dotproduct(x, y)));
  return result(a, b);
}
PURGEN
  • 47
  • 8