Emmanuel Akinfulubi

JavaScriptMath

Matrix multiplication and determinant in JavaScript

Intermediate · 5 min read

A matrix is a grid of numbers, like a small spreadsheet. Matrices are how games rotate and move 3D models, how image filters blur photos, and how a lot of machine learning does its sums. In JavaScript, a matrix is simply an array of rows, where each row is an array of numbers.

In this tutorial you will multiply two matrices, refusing shapes that don't fit, and compute the determinant, a single number that tells you whether a matrix can be undone. You will check two famous rules with whole numbers, see them wobble when the entries are decimals like 0.1, and finish by measuring the area of a plot of land with a 2 by 2 determinant. You need to know nested for loops, map, filter and what recursion is.

Rows and columns

JavaScript

const A = [[1, 2, 3], [4, 5, 6], [7, 8, 10]];
console.log(A[1][2], A.length, A[0].length); // 6 3 3

A[1][2] is row 1, column 2, counting from 0. A matrix with 3 rows and 3 columns is called "3 by 3".

How matrix multiplication works

To multiply A by B, each entry of the answer comes from one row of A and one column of B. Multiply them in pairs, first with first, second with second, and add up. That is called a dot product. For it to work, a row of A must be as long as a column of B: the number of columns in A must equal the number of rows in B.

Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.

111 Matrix multiplication and the determinant

fair

Multiply two 3 by 3 matrices, refusing shapes that do not fit, and compute determinants of any size by cofactor expansion. Check that det(AB) equals det(A) * det(B), that a matrix times its inverse is the identity, and then check both again with entries like 0.1. Finish by measuring a plot of land with the same 2 by 2 determinant.

Stuck? Three hints, smallest first
  1. 1. Entry (i, j) of a product is row i of the left dotted with column j of the right, so the inner dimensions must match.
  2. 2. For a determinant, expand along the first row: alternate signs, and recurse on the matrix with that row and column deleted.
  3. 3. A 2 by 2 determinant is the cross product of two vectors, which is twice the area of the triangle they span.

Step 1: multiply, with a shape check

Step 1

const shape = (m) => [m.length, m[0].length];
function multiply(a, b) {
  const [rowsA, colsA] = shape(a);
  const [rowsB, colsB] = shape(b);
  if (colsA !== rowsB) {
    throw new RangeError('cannot multiply ' + rowsA + 'x' + colsA + ' by ' + rowsB + 'x' + colsB);
  }
  const out = [];
  for (let i = 0; i < rowsA; i++) {
    const row = [];
    for (let j = 0; j < colsB; j++) {
      let total = 0;
      for (let k = 0; k < colsA; k++) total += a[i][k] * b[k][j];
      row.push(total);
    }
    out.push(row);
  }
  return out;
}
const B = [[2, 0, 1], [1, 3, 0], [0, 1, 4]];
console.log(JSON.stringify(multiply(A, B))); // [[4,9,13],[13,21,28],[22,34,47]]
console.log(JSON.stringify(multiply(B, A))); // [[9,12,16],[13,17,21],[32,37,46]]

Three loops: i picks the row of A, j picks the column of B, and k walks along both to build the dot product. JSON.stringify prints the grid on one line.

Notice that A times B and B times A are different. With ordinary numbers, 2 * 3 equals 3 * 2. With matrices, order matters.

Step 2: why the shape check matters

Step 2

let mismatch = 'no error';
try { multiply(A, [[4, 7], [2, 6]]); } catch (error) { mismatch = error.constructor.name + ': ' + error.message; }
console.log(mismatch); // RangeError: cannot multiply 3x3 by 2x2

Without the check, this pair crashes deep inside the loop with "Cannot read properties of undefined", because it asks for a row 2 that the 2 by 2 matrix doesn't have. The other way round is worse: a 2 by 2 times a 3 by 3 quietly uses only two of the three rows and returns a wrong answer. A clear error with both shapes in it is much easier to fix.

Step 3: the determinant, by expanding a row

For a 2 by 2 matrix [[a, b], [c, d]], the determinant is a * d - b * c. For anything bigger, go along the first row. For each entry, delete its row and column to get a smaller matrix (the minor), take that matrix's determinant, multiply, and add the results with signs that alternate +, -, +, ...

Step 3

const minor = (m, row, col) =>
  m.filter((_, i) => i !== row).map((r) => r.filter((_, j) => j !== col));
function det(m) {
  const n = m.length;
  if (n === 1) return m[0][0];
  if (n === 2) return m[0][0] * m[1][1] - m[0][1] * m[1][0];
  let total = 0;
  for (let j = 0; j < n; j++) total += (j % 2 ? -1 : 1) * m[0][j] * det(minor(m, 0, j));
  return total;
}
console.log(det(A), det(B)); // -3 25

det calls itself on smaller and smaller matrices until it reaches 2 by 2. That is recursion. (j % 2 ? -1 : 1) gives the alternating sign. _ is a name for an argument you don't use.

This method takes a huge number of multiplications for big matrices, so it suits 3 by 3 or 4 by 4. Larger grids use other methods.

Step 4: the product rule

Step 4

console.log(det(multiply(A, B)), det(A) * det(B)); // -75 -75
const singular = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
console.log(det(singular)); // 0

The determinant of a product is the product of the determinants. A determinant of 0 means the rows depend on each other (here, row 3 is row 2 plus the difference between row 2 and row 1), and the matrix can't be undone. It is called singular.

Step 5: the inverse of a 2 by 2

The inverse undoes a matrix: a matrix times its inverse gives the identity, which has 1s down the diagonal and 0s elsewhere.

Step 5

function inverse2(m) {
  const d = det(m);
  if (d === 0) return null;
  return [[m[1][1] / d, -m[0][1] / d], [-m[1][0] / d, m[0][0] / d]];
}
const M = [[4, 7], [2, 6]];
console.log(JSON.stringify(multiply(M, inverse2(M)))); // [[0.9999999999999998,4.440892098500626e-16],[-2.220446049250313e-16,1.0000000000000004]]

This should be [[1, 0], [0, 1]]. The determinant is 10, and dividing by 10 makes decimals that can't be stored exactly, so the result is very close to the identity, but not equal.

Step 6: the product rule with decimals

Step 6

const F = [[0.1, 0.2], [0.3, 0.4]];
const G = [[0.5, 0.6], [0.7, 0.8]];
console.log(det(multiply(F, G)), det(F) * det(G)); // 0.0003999999999999976 0.00039999999999999904

The rule that held exactly for whole numbers now misses by a tiny amount. So never test det(m) === 0 on measured data, and never expect an inverse to come back exactly. Compare against a small tolerance instead.

Step 7: measure a plot of land

A 2 by 2 determinant made from two corner points is twice the area of the triangle between them and the origin. Add these up around a shape, and you get the shoelace formula for its area:

Step 7

function area(points) {
  let total = 0;
  for (let i = 0; i < points.length; i++) {
    const p = points[i];
    const q = points[(i + 1) % points.length];
    total += det([[p[0], q[0]], [p[1], q[1]]]);
  }
  return total / 2;
}
const plot = [[0, 0], [40, 0], [40, 25], [15, 40], [0, 25]];
console.log(area(plot), area(plot.slice().reverse())); // 1300 -1300

(i + 1) % points.length wraps the last corner back round to the first. The plot comes to 1300 square meters. Listing the corners the other way round gives -1300: the sign tells you which way round you went.

The full solution

The answer panel has multiply, identity, minor, det, inverse2 and area, and also checks a 4 by 4 determinant and a transpose. Press Run to see the output.

The answer

const shape = (m) => [m.length, m[0].length];

function multiply(a, b) {
  const [rowsA, colsA] = shape(a);
  const [rowsB, colsB] = shape(b);
  if (colsA !== rowsB) {
    throw new RangeError('cannot multiply ' + rowsA + 'x' + colsA + ' by ' + rowsB + 'x' + colsB);
  }
  const out = [];
  for (let i = 0; i < rowsA; i++) {
    const row = [];
    for (let j = 0; j < colsB; j++) {
      let total = 0;
      for (let k = 0; k < colsA; k++) total += a[i][k] * b[k][j];
      row.push(total);
    }
    out.push(row);
  }
  return out;
}

const identity = (n) =>
  Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => (i === j ? 1 : 0)));

// Drop one row and one column.
const minor = (m, row, col) =>
  m.filter((_, i) => i !== row).map((r) => r.filter((_, j) => j !== col));

function det(m) {
  const n = m.length;
  if (n === 1) return m[0][0];
  if (n === 2) return m[0][0] * m[1][1] - m[0][1] * m[1][0];
  let total = 0;
  for (let j = 0; j < n; j++) total += (j % 2 ? -1 : 1) * m[0][j] * det(minor(m, 0, j));
  return total;
}

function inverse2(m) {
  const d = det(m);
  if (d === 0) return null;
  return [[m[1][1] / d, -m[0][1] / d], [-m[1][0] / d, m[0][0] / d]];
}

// The shoelace formula, written as a sum of 2 by 2 determinants.
function area(points) {
  let total = 0;
  for (let i = 0; i < points.length; i++) {
    const p = points[i];
    const q = points[(i + 1) % points.length];
    total += det([[p[0], q[0]], [p[1], q[1]]]);
  }
  return total / 2;
}

const A = [[1, 2, 3], [4, 5, 6], [7, 8, 10]];
const B = [[2, 0, 1], [1, 3, 0], [0, 1, 4]];
const singular = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const fourByFour = [[1, 0, 2, -1], [3, 0, 0, 5], [2, 1, 4, -3], [1, 0, 5, 0]];
const M = [[4, 7], [2, 6]];
const F = [[0.1, 0.2], [0.3, 0.4]];
const G = [[0.5, 0.6], [0.7, 0.8]];
const plot = [[0, 0], [40, 0], [40, 25], [15, 40], [0, 25]];

let mismatch = 'no error';
try { multiply(A, M); } catch (error) { mismatch = error.constructor.name + ': ' + error.message; }

console.log('A B          :', multiply(A, B));
console.log('B A          :', multiply(B, A), '<- a different matrix');
console.log('dets         :', det(A), det(B), 'product', det(A) * det(B), 'det of AB', det(multiply(A, B)));
console.log('4 by 4       :', det(fourByFour), 'transpose of A', det([0, 1, 2].map((j) => A.map((r) => r[j]))));
console.log('singular     :', det(singular), 'inverse of a singular 2 by 2', inverse2([[1, 2], [2, 4]]));
console.log('M times M^-1 :', multiply(M, inverse2(M)), '<- not quite the identity');
console.log('float dets   :', det(multiply(F, G)), det(F) * det(G));
console.log('shape error  :', mismatch);
console.log('plot         :', area(plot), 'square metres, reversed', area(plot.slice().reverse()));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the product is row by column, and swapping the operands changes it', [multiply(A, B), multiply(B, A)], [[[4, 9, 13], [13, 21, 28], [22, 34, 47]], [[9, 12, 16], [13, 17, 21], [32, 37, 46]]]);
test('the identity leaves a matrix alone, and mismatched shapes throw', [multiply(A, identity(3)), mismatch], [A, 'RangeError: cannot multiply 3x3 by 2x2']);
test('det(AB) is det(A) times det(B), exactly, in whole numbers', [det(A), det(B), det(multiply(A, B)), det(A) * det(B)], [-3, 25, -75, -75]);
test('cofactor expansion handles 4 by 4, and a transpose has the same determinant', [det(fourByFour), det([0, 1, 2].map((j) => A.map((r) => r[j])))], [30, -3]);
test('a determinant of 0 means the rows are dependent, and there is no inverse', [det(singular), inverse2([[1, 2], [2, 4]])], [0, null]);
test('a matrix times its own inverse is NOT the identity in floating point', multiply(M, inverse2(M)), [[0.9999999999999998, 4.440892098500626e-16], [-2.220446049250313e-16, 1.0000000000000004]]);
test('and with 0.1 entries the same identity fails, by 1.46e-18', [det(multiply(F, G)), det(F) * det(G), det(multiply(F, G)) === det(F) * det(G)], [0.0003999999999999976, 0.00039999999999999904, false]);
test('the shoelace formula is a sum of 2 by 2 determinants: 1300 square metres', [area(plot), area(plot.slice().reverse())], [1300, -1300]);
test('and a 2 by 2 determinant is twice the triangle its two vectors span', det([[3, 0], [0, 4]]) / 2, 6);

Two things are worth taking from the shape of this code. Multiplication is three nested loops and a dimension check, and the check is not optional: colsA !== rowsB is the one error the algorithm can detect for you, and without it a mismatched multiply silently produces NaN entries from undefined reads. And the determinant is naturally recursive — expand along the first row, alternate signs, recurse on the minor — which is beautiful and costs n! multiplications. Fine at 4 by 4, hopeless at 20 by 20, where you would use LU decomposition instead.

Then the floating point. With whole-number entries every identity here holds exactly: det(AB) = det(A) det(B) lands on -75 both ways, a transpose has the same determinant, a singular matrix gives exactly 0. Swap in entries of 0.1 and the same identity misses by 1.46e-18, and M times its own inverse comes back with 0.9999999999999998 and 1.0000000000000004 on the diagonal and 4.4e-16 off it. So never test a matrix for invertibility with det(m) === 0 on measured data, and never assert an inverse round-trips exactly; compare against a tolerance scaled to the size of the entries.

The last two assertions connect this back to geometry. A 2 by 2 determinant is the cross product of two vectors and twice the area of the triangle they span, which means the shoelace formula from exercise 75 is literally a sum of determinants around the polygon — the 40 by 25 plot with a corner cut off comes to 1300 square metres, and listing the corners the other way round gives -1300. The sign is the winding direction, and it is the determinant telling you the orientation was flipped.

Common mistakes

  • Skipping the shape check. Mismatched matrices crash with a confusing message or give a wrong answer, instead of a clear error.
  • Assuming A times B equals B times A. For matrices it usually doesn't.
  • Comparing decimal results with ===. Use a tolerance, like Math.abs(x - y) < 1e-9.

Try it yourself

  1. Multiply A by identity(3) and check that you get A back.
  2. Work out the determinant of [[2, 0, 0], [0, 3, 0], [0, 0, 4]] by hand, then with det.
  3. Write transpose(m), which swaps rows and columns, and check that det gives the same answer for A and its transpose.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.