Flying memes

Determinant of a matrix in JS

I’m currently reading Deep Learning, from Ian Goodfellow, Yoshua Bengio and Aaron Courville. While reading I got interested in calculating the determinant of a square matrix, I know there are many existing libraries to do that but the algorithm looked simply enough to give it a try.


Here’s my solution:

function det(m) {
  var size = Math.sqrt(m.length);
  if (size % 1 !== 0) {
    return null;
  }
  if (size === 2) {
    return m[0] * m[3] - m[1] * m[2];
  }
  return m.slice(0, size).reduce(function(t, v, i) {
    var sub = [];
    for (var r = size; r < m.length; r += size) {
      sub = sub.concat(
        m.slice(r, r + i), 
        m.slice(r + i + 1, r + size)
      );
    }
    return t + (i % 2 === 0 ? -1 : 1) * v * det(sub);
  }, 0);
}

The idea is to use a single array to define a matrix and the extract the length from using Math.sqrt, eg:

var matrix = [
 1, 2, 3,
 4, 5, 6,
 6, 7, 8
];
var d = det(matrix); // 0

A running example can be found on JSFiddle.

Tags: ,