Last updated: 2026-11-26

24. Matrices

For new readers

Matrices carry the transforms that are not versors (non-uniform scaling, shearing) and the composite transforms of shapes and the camera. Here the determinant, the minors and the inverse are worked out with the wedge product of the algebra, and checked against the classical methods.

Matrices

The book builds 4×4 matrices, multiplication, transposition and inversion by cofactor expansion. The interface stays the book's: a matrix is a list of rows and M[r][c] reads an element. What changes is where the mathematics comes from. The columns of a matrix are vectors, and in geometric algebra the quantities this page builds by hand are already products of those vectors.

Step 1 — columns are vectors, determinants are wedges

Read column c of an n×n matrix as the vector a_c = Σ_r M[r][c] e_r in the subspace spanned by e1 e2 e3 e+ (Euclidean metric, so nothing about the conformal part leaks in). The outer product of all the columns is a multiple of the pseudoscalar E = e1…en, and that multiple is the determinant:

a0 ∧ a1 = (e1 − 3 e2) ∧ (5 e1 + 2 e2)
        = (1·2 − (−3)·5) e1∧e2  = 17 e12          →  det [[1,5],[−3,2]] = 17

The same coefficient rule gives every minor. Wedge together all columns except column c; the result is an (n−1)-vector whose coefficient on the basis blade E_r (the pseudoscalar with e_r removed) is the minor M_rc — the determinant of the submatrix with row r and column c deleted. The book's recursive definition falls out of how wedge products expand.

# wedge product of the columns of m, leaving out column `skip` (-1 = none)
make a function called mat_wedge takes m, skip returns w
  let w = ga_scalar(1)
  let c = 0
  while c < m.length do
    if c != skip then
      let w = ga_outer(w, mat_col(m, c))
    end
    let c = c + 1
  end
  return w
end

make a function called mat_pseudo_mask takes m returns mask
  return (1 shl m.length) - 1
end

make a function called determinant takes m returns d
  let w = mat_wedge(m, -1)
  return w[mat_pseudo_mask(m)]
end

make a function called minor takes m, r, c returns v
  let w = mat_wedge(m, c)
  return w[mat_pseudo_mask(m) - (1 shl r)]
end

make a function called cofactor takes m, r, c returns v
  let k = minor(m, r, c)
  if (r + c) % 2 == 1 then
    return 0 - k
  end
  return k
end

make a function called is_invertible takes m returns ok
  return determinant(m) != 0
end

submatrix is plain list surgery; the tests use it only to build an independent check (below).

# the matrix with row `skip_r` and column `skip_c` deleted
make a function called submatrix takes m, skip_r, skip_c returns s
  let s = []
  let r = 0
  while r < m.length do
    if r != skip_r then
      let row = []
      let c = 0
      while c < m.length do
        if c != skip_c then
          let row = list_push(row, m[r][c])
        end
        let c = c + 1
      end
      let s = list_push(s, row)
    end
    let r = r + 1
  end
  return s
end

Step 2 — the inverse is the reciprocal frame

If the columns of A are a_0 … a_{n−1}, the rows of A⁻¹ are the vectors a^c with a^c · a_j = δ_cj: the reciprocal frame, given in closed form by

a^c = (−1)^c (a_0 ∧ … omit a_c … ∧ a_{n−1}) I⁻¹,     I = a_0 ∧ … ∧ a_{n−1}

and I⁻¹ = reverse(I) / (I · reverse(I)). Dividing by the pseudoscalar's norm is the "divide by the determinant" step of the book's algorithm; the wedge of the other columns supplies the cofactors, so the matrix of cofactors and its transpose are never formed.

# Reciprocal frame: row c of the inverse is  (-1)^c W_c I^-1  with
# W_c = wedge of the other columns and I^-1 = reverse(I) / (I reverse(I)).
make a function called inverse takes m returns inv
  let big_i = mat_wedge(m, -1)
  let rev_i = ga_reverse(big_i)
  let norm = ga_gp(big_i, rev_i)
  if norm[0] == 0 then
    print("inverse: matrix is not invertible")
    return []
  end
  let i_inv = ga_scale(rev_i, 1 / norm[0])
  let inv = []
  let c = 0
  while c < m.length do
    let a = ga_gp(mat_wedge(m, c), i_inv)
    if c % 2 == 1 then
      let a = ga_neg(a)
    end
    let row = []
    let k = 0
    while k < m.length do
      let row = list_push(row, a[1 shl k])
      let k = k + 1
    end
    let inv = list_push(inv, row)
    let c = c + 1
  end
  return inv
end

Step 3 — products

Each entry of A·B is the dot product of a row of A with a column of B — the book says so itself. Here that dot product is the scalar part of the geometric product of the two vectors, so no separate multiply-and-add loop is written. A matrix times a tuple multiplies the tuple's (x, y, z, w), then re-embeds the result as a conformal tuple.

# vector sum of coeffs[i] e_i  (i = 0..3)
make a function called mat_vec takes coeffs returns v
  let v = ga_zero()
  let i = 0
  while i < coeffs.length do
    let v = list_set(v, 1 shl i, coeffs[i])
    let i = i + 1
  end
  return v
end

make a function called mat_col takes m, c returns v
  let coeffs = []
  let r = 0
  while r < m.length do
    let coeffs = list_push(coeffs, m[r][c])
    let r = r + 1
  end
  return mat_vec(coeffs)
end

make a function called mat_row takes m, r returns v
  return mat_vec(m[r])
end

make a function called identity_matrix returns m
  return [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
end

make a function called mat_eq takes a, b returns ok
  if a.length != b.length then
    return false
  end
  let r = 0
  while r < a.length do
    let c = 0
    while c < a.length do
      if not equal(a[r][c], b[r][c]) then
        return false
      end
      let c = c + 1
    end
    let r = r + 1
  end
  return true
end

# dot product of two vectors: the scalar part of their geometric product
make a function called mat_dot takes u, v returns d
  return ga_vec_dot(u, v)
end

make a function called mat_mul takes a, b returns m
  let n = a.length
  let cols = []
  let c = 0
  while c < n do
    let cols = list_push(cols, mat_col(b, c))
    let c = c + 1
  end
  let m = []
  let r = 0
  while r < n do
    let row_vec = mat_row(a, r)
    let row = []
    let c = 0
    while c < n do
      let row = list_push(row, mat_dot(row_vec, cols[c]))
      let c = c + 1
    end
    let m = list_push(m, row)
    let r = r + 1
  end
  return m
end

# matrix * tuple: the tuple's (x, y, z, w) is the column being multiplied;
# the result is re-embedded as a conformal tuple.
# a matrix times a tuple: the four dot products of the matrix's rows with (x, y, z, w),
# written out (mat_tuple_ga below is the same thing through multivector rows, the
# definition; the test tree, foundations/matrices/multiply/times_tuple/ways, checks they agree exactly). Every ray, hit and
# normal goes through this, so it must not build a multivector per row.
make a function called mat_tuple takes m, t returns result
  let x = get_x(t)
  let y = get_y(t)
  let z = get_z(t)
  let w = get_w(t)
  let a = m[0]
  let b = m[1]
  let c = m[2]
  let d = m[3]
  return tuple(a[0] * x + a[1] * y + a[2] * z + a[3] * w, b[0] * x + b[1] * y + b[2] * z + b[3] * w, c[0] * x + c[1] * y + c[2] * z + c[3] * w, d[0] * x + d[1] * y + d[2] * z + d[3] * w)
end

Step 4 — checks

Worked values come from tools/oracle.py, which multiplies, expands determinants and inverts (adjugate over determinant) with exact fractions in plain Python: a product, a matrix applied to a point, the determinants of a 4 × 4 and a 3 × 3 matrix, a minor and a cofactor, and a whole inverse. The wedge-product results are also checked against laws and methods that share none of their code:

  • every determinant against a first-row Laplace expansion (an agree node: the plain recursive method and the algebra must give the same numbers);
  • M · inverse(M) = I exactly, both ways round, with exact rationals;
  • det(AB) = det(A)·det(B), (AB)ᵀ = BᵀAᵀ, cofactor signs, and a matrix with two equal rows that cannot be inverted.

Step 5 — Putting it together: the four experiments

# Chapter 3, "Putting It Together": the book's four experiments.
include "../lib/spec.patlang"
include "../lib/matrix.patlang"

make a function called show takes m returns s
  let out = sb_new()
  let r = 0
  while r < m.length do
    sb_push(out, "  " + m[r][0] + " " + m[r][1] + " " + m[r][2] + " " + m[r][3] + chr(10))
    let r = r + 1
  end
  return sb_str(out)
end

let a = [[3, -9, 7, 3], [3, -8, 2, -9], [-4, 4, 4, 1], [-6, 5, -1, 1]]

print("1. Inverting the identity matrix:")
print(show(inverse(identity_matrix())))

print("2. A * inverse(A):")
print(show(mat_mul(a, inverse(a))))

print("3. inverse(transpose(A)) and transpose(inverse(A)) are the same matrix: " + mat_eq(inverse(transpose(a)), transpose(inverse(a))))

print("4. Change one element of the identity, then multiply a tuple by it.")
let t = tuple(1, 2, 3, 1)
let k = 0
while k < 4 do
  let m = identity_matrix()
  let m = list_set(m, k, list_set(m[k], k, 5))
  let r = mat_tuple(m, t)
  print("  identity[" + k + "][" + k + "] = 5  ->  (" + get_x(r) + ", " + get_y(r) + ", " + get_z(r) + ", w=" + get_w(r) + ")")
  let k = k + 1
end
> v2_interp.exe examples/ch03_experiments.patlang
1. Inverting the identity matrix:
  1 0 0 0
  0 1 0 0
  0 0 1 0
  0 0 0 1

2. A * inverse(A):
  1 0 0 0
  0 1 0 0
  0 0 1 0
  0 0 0 1

3. inverse(transpose(A)) and transpose(inverse(A)) are the same matrix: true
4. Change one element of the identity, then multiply a tuple by it.
  identity[0][0] = 5  ->  (5, 2, 3, w=1)
  identity[1][1] = 5  ->  (1, 10, 3, w=1)
  identity[2][2] = 5  ->  (1, 2, 15, w=1)
  identity[3][3] = 5  ->  (1, 2, 3, w=5)
  1. The inverse of the identity is the identity.
  2. A matrix times its inverse is the identity, exactly (the entries are rationals, so there is no round-off to excuse).
  3. Inverting then transposing equals transposing then inverting.
  4. Changing a diagonal element of the identity to 5 scales that coordinate of the tuple by 5. For the last diagonal element that coordinate is w: the result is a weighted point, (1, 2, 3) with weight 5, i.e. the point (1/5, 2/5, 3/5) once the weight is divided out.

Step 6 — cost, measured

Call counts doubled from 250 to 2000 (each timing is the whole batch):

calls mat_tuple mat_mul inverse
250 97 ms 210 ms 278 ms
500 182 ms 423 ms 553 ms
1000 361 ms 826 ms 1 142 ms
2000 721 ms 1 672 ms 2 238 ms

Linear in the number of calls, as it should be. In absolute terms, one mat_tuple is about 0.36 ms. That is acceptable for this page and will not be for a renderer that transforms two tuples per ray per object. The cost is the generic 32-component product being used for 4-component vectors; it will be addressed where it first matters, with an equivalence test against this implementation, not before.slow for ray tracing; see the fast page

Follow-up: Rays, spheres and planes removed most of this cost with the scalar product (the table above is the Matrices measurement and is left as measured).

How it is checked

> v2_interp.exe tests/run.patlang --node foundations/matrices --depth 2
[ ok ] Matrices
[ ok ]   Multiplying
[ ok ]     A times B, against the independent oracle
[ ok ]     The identity changes nothing, on either side
[ ok ]     (AB)C = A(BC)
[ ok ]     AB and BA differ in general
[ ok ]     A matrix times a tuple
[ ok ]   Transposing
[ ok ]     Transposing twice gives the matrix back; the identity is its own transpose
[ ok ]     The transpose of a product is the product of transposes, reversed
[ ok ]   Determinants
[ ok ]     Worked determinants, minors and cofactors against the oracle
[ ok ]     A submatrix drops one row and one column
[ ok ]     det(AB) = det(A) det(B)
[ ok ]     A cofactor is the minor with sign (-1)^(r+c)
[ ok ]     Two ways to find a determinant  (all, giving the same answer)
[ ok ]   Inverting
[ ok ]     The inverse of A, against the oracle (adjugate over determinant)
[ ok ]     M times its inverse is the identity, both ways round, exactly
[ ok ]     Multiplying by B then by B's inverse gives A back
[ ok ]     A matrix with two equal rows cannot be inverted
checks: 19 passed, 0 failed, 0 blocked, 0 skipped, 0 not run
ALL PASSED