TExcelTAD
Home › Math for Games › Matrix Inverse

Matrix Inverse

The inverse of a matrix undoes it: M⁻¹ * M = I. If M takes a point from a model's local space into the world, M⁻¹ takes a world point back into local space. Games need that all the time: "where is the player relative to this door?", turning a camera's transform into a view matrix, converting a mouse ray into an object's space for picking.

Cheap inverses for the matrices games use

A general 4×4 inverse is relatively expensive, but game transforms are built from pieces whose inverses are trivial:

Transform Inverse
translate(t) translate(-t)
scale(s) scale(1/s) (impossible if any factor is 0)
rotation R its transpose Rᵀ (rows become columns)
A * B B⁻¹ * A⁻¹ (reverse the order!)

The rotation rule works because a rotation's columns are perpendicular unit vectors (an orthonormal matrix). So the inverse of T * R * S is S⁻¹ * Rᵀ * T⁻¹, with no general-purpose algorithm needed.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <numbers>

struct Vec3 { double x, y, z; };
struct Mat4 {
    double m[4][4]{};
    static Mat4 identity() { Mat4 r; for (int i = 0; i < 4; i++) r.m[i][i] = 1; return r; }
};
Mat4 operator*(const Mat4& A, const Mat4& B) {
    Mat4 R;
    for (int r = 0; r < 4; r++)
        for (int c = 0; c < 4; c++)
            for (int k = 0; k < 4; k++) R.m[r][c] += A.m[r][k] * B.m[k][c];
    return R;
}
Vec3 transformPoint(const Mat4& M, Vec3 p) {
    return {M.m[0][0] * p.x + M.m[0][1] * p.y + M.m[0][2] * p.z + M.m[0][3],
            M.m[1][0] * p.x + M.m[1][1] * p.y + M.m[1][2] * p.z + M.m[1][3],
            M.m[2][0] * p.x + M.m[2][1] * p.y + M.m[2][2] * p.z + M.m[2][3]};
}
Mat4 translate(Vec3 t) { Mat4 r = Mat4::identity(); r.m[0][3] = t.x; r.m[1][3] = t.y; r.m[2][3] = t.z; return r; }
Mat4 scale(Vec3 s) { Mat4 r = Mat4::identity(); r.m[0][0] = s.x; r.m[1][1] = s.y; r.m[2][2] = s.z; return r; }
Mat4 rotateY(double a) {
    Mat4 r = Mat4::identity(); double c = std::cos(a), s = std::sin(a);
    r.m[0][0] = c; r.m[0][2] = s; r.m[2][0] = -s; r.m[2][2] = c; return r;
}
Mat4 transpose(const Mat4& M) {
    Mat4 r; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) r.m[i][j] = M.m[j][i]; return r;
}
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, Vec3 v) {
    return os << "(" << z0(v.x) << ", " << z0(v.y) << ", " << z0(v.z) << ")";
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    Vec3 pos{4, 0, 2}, scl{2, 2, 2};
    double yaw = std::numbers::pi / 6;          // 30 degrees
    Mat4 R = rotateY(yaw);

    Mat4 model = translate(pos) * R * scale(scl);
    Mat4 inv = scale({1 / scl.x, 1 / scl.y, 1 / scl.z}) * transpose(R) * translate({-pos.x, -pos.y, -pos.z});

    Vec3 local{1, 0.5, -1};
    Vec3 world = transformPoint(model, local);
    std::cout << "local -> world: " << world << "\n";
    std::cout << "world -> local: " << transformPoint(inv, world) << "\n";

    Mat4 check = inv * model;                   // should be the identity
    std::cout << "inv * model diagonal: " << z0(check.m[0][0]) << " " << z0(check.m[1][1]) << " "
              << z0(check.m[2][2]) << " " << z0(check.m[3][3]) << ", corner m[0][3] = " << z0(check.m[0][3]) << "\n";
}
local -> world: (4.732, 1.000, -0.732)
world -> local: (1.000, 0.500, -1.000)
inv * model diagonal: 1.000 1.000 1.000 1.000, corner m[0][3] = 0.000

Using it: "where is the player relative to me?"

Bring the player's world position into a guard's local space, and questions become simple comparisons: local z < 0 means in front (our guards look down -Z), local x > 0 means to the right. A trigger box is an axis-aligned test in the box's own space, however the box is rotated in the world.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <numbers>

struct Vec3 { double x, y, z; };

// Rigid transform (rotation about Y + position): world -> local is
// "subtract the position, then rotate by the transpose".
struct Pose { Vec3 pos; double yaw; };

Vec3 worldToLocal(const Pose& p, Vec3 w) {
    double dx = w.x - p.pos.x, dy = w.y - p.pos.y, dz = w.z - p.pos.z;
    double c = std::cos(p.yaw), s = std::sin(p.yaw);
    // transpose of rotateY: rows and columns swapped
    return {c * dx - s * dz, dy, s * dx + c * dz};
}

double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }

int main() {
    std::cout << std::fixed << std::setprecision(2);
    Pose guard{{10, 0, 10}, std::numbers::pi / 2};       // turned 90 deg left: looks down -X
    Vec3 players[] = {{6, 0, 9}, {14, 0, 11}, {10, 0, 7}, {8, 0, 13}};
    for (Vec3 w : players) {
        Vec3 l = worldToLocal(guard, w);
        std::cout << "world (" << w.x << ", " << w.z << ") -> local (" << z0(l.x) << ", " << z0(l.z) << "): "
                  << (l.z < 0 ? "in front" : "behind") << ", " << (l.x > 0 ? "right" : "left") << "\n";
    }
}
world (6.00, 9.00) -> local (1.00, -4.00): in front, right
world (14.00, 11.00) -> local (-1.00, 4.00): behind, left
world (10.00, 7.00) -> local (3.00, 0.00): in front, right
world (8.00, 13.00) -> local (-3.00, -2.00): in front, left

The general inverse

Sometimes you really do have an arbitrary matrix: a projection, a combination with shear, or one that came from a file. Then you need a general inverse. Libraries use cofactor expansion for 4×4 (glm::inverse); the simplest method to read is Gauss-Jordan elimination, shown here. If a pivot is (near) zero, the matrix is singular and has no inverse: a scale of 0 squashed a dimension away and nothing can bring it back.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <utility>

struct Mat4 { double m[4][4]{}; };

bool inverse(const Mat4& in, Mat4& out) {
    double a[4][8];
    for (int r = 0; r < 4; r++)
        for (int c = 0; c < 8; c++) a[r][c] = c < 4 ? in.m[r][c] : (c - 4 == r ? 1 : 0);
    for (int col = 0; col < 4; col++) {
        int pivot = col;                                  // partial pivoting: largest entry
        for (int r = col + 1; r < 4; r++)
            if (std::fabs(a[r][col]) > std::fabs(a[pivot][col])) pivot = r;
        if (std::fabs(a[pivot][col]) < 1e-12) return false;   // singular
        for (int c = 0; c < 8; c++) std::swap(a[col][c], a[pivot][c]);
        double p = a[col][col];
        for (int c = 0; c < 8; c++) a[col][c] /= p;
        for (int r = 0; r < 4; r++) {
            if (r == col) continue;
            double f = a[r][col];
            for (int c = 0; c < 8; c++) a[r][c] -= f * a[col][c];
        }
    }
    for (int r = 0; r < 4; r++)
        for (int c = 0; c < 4; c++) out.m[r][c] = a[r][c + 4];
    return true;
}

double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }

int main() {
    std::cout << std::fixed << std::setprecision(3);
    Mat4 shear{{{1, 0.5, 0, 2}, {0, 1, 0, 0}, {0, 0, 2, -1}, {0, 0, 0, 1}}};
    Mat4 inv;
    if (inverse(shear, inv)) {
        std::cout << "inverse:\n";
        for (auto& row : inv.m) {
            for (double v : row) std::cout << std::setw(8) << z0(v);
            std::cout << "\n";
        }
    }
    Mat4 flat{{{1, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}};   // scale y by 0
    std::cout << "flat matrix invertible? " << (inverse(flat, inv) ? "yes" : "no") << "\n";
}
inverse:
   1.000  -0.500   0.000  -2.000
   0.000   1.000   0.000   0.000
   0.000   0.000   0.500   0.500
   0.000   0.000   0.000   1.000
flat matrix invertible? no

Tip: Don't invert a matrix every frame if you can keep both directions. Engines cache worldToLocal next to localToWorld and recompute it only when the transform changes. And never invert a matrix with a zero scale: an object scaled to 0 "to hide it" will produce NaN for anything that needs its inverse.

Test yourself

What is the inverse of a pure rotation matrix?

  1. Its negation
  2. Its transpose
  3. The identity
  4. It has none

What is the inverse of A * B?

  1. A⁻¹ * B⁻¹
  2. B⁻¹ * A⁻¹
  3. B * A
  4. A * B transposed

When does a matrix have no inverse?

  1. When it contains a rotation
  2. When it contains a translation
  3. When it squashes a dimension, e.g. a scale of 0
  4. When it is 4×4