Matrices, from scratch

glint · Examples · Tutorials · Gallery

For when matrices haven't clicked, or you never did them at school: rules that move points, what a matrix really is (where the axes go), working them out by hand, writing one from a description, columns and rows, the determinant, rotation worked out, multiplying and order, why shaders work backwards, moving with an extra 1, then 3D: the x-y-z pattern, the p.xz *= rot(a) shorthand, turning space in a raymarcher, world vs own axes, gimbal lock, any axis, look-at, blending rotations, and mat4 with perspective.

A free interactive course of 26 steps in glint, a live shader editor in the browser: each step changes a running shader, and ticks itself when you've done its task.

1. Moving every point at once

No matrices yet. Start with something simpler: a rule that takes a point and gives back a new point. apply below is one. The picture runs it on a grid of dots (and the lines between them), so you can see what the rule does to the whole plane at once.

Right now it hands every point back unchanged, so the dots sit on the grid. The orange dots are the top-right quarter, so you can follow them, and the white one is (0, 0), the origin. The red and green arrows show where the rule sends a step to the right and a step up; they'll matter soon.

Some rules to try, one at a time:

v * 2.0            // twice as big
v * 0.5            // half the size
vec2(-v.x, v.y)    // a mirror
vec2(v.y, v.x)     // swap x and y
v + vec2(0.1, 0.0) // slide right

Your turn: Mirror it left to right: return vec2(-v.x, v.y); The orange dots jump to the left.

2. The rules a matrix can do

Look at the mirror again, written out in full: new x = -1 × x + 0 × y, and new y = 0 × x + 1 × y. Each new number is some amount of x plus some amount of y, and nothing else. Those are exactly the rules a matrix can do.

The rule below is one too. Points slide right by half their height, so the grid leans:

new x = 1 × x + 0.5 × y
new y = 0 × x + 1 × y

Notice what it keeps: straight lines stay straight, parallel lines stay parallel, evenly spaced dots stay evenly spaced, and (0, 0) stays put. Every matrix keeps those.

Anything else breaks them. Squaring a number bends the lines; adding a fixed amount moves (0, 0). Neither is a matrix (the second one can be done with a trick, later on).

Your turn: See a rule that isn't a matrix: change 0.5 * v.y to 3.0 * v.y * v.y. The straight lines bend.

3. Every point is made of two arrows

Forget matrices for a moment. Take the point (3, 2). It means: go 3 steps along x, then 2 steps along y. With an arrow X = (1, 0) for 'one step along x' and Y = (0, 1) for 'one step along y', the point is 3 × X + 2 × Y.

Every point works like that: (a, b) is a × X + b × Y. So here's the big idea: if you change what X and Y are, every point changes with them, because every point is built out of them.

That's what apply does below: v.x * X + v.y * Y. The red arrow is X, the green one is Y. Right now they're the normal axes, so nothing moves. The pink path is the recipe for the orange dot 3 across and 2 up: 3 dot-steps along X, then 2 along Y.

Say Y becomes (0.5, 1): one step 'up' now also moves half a step right. The point (0, 2) lands at 0 × X + 2 × Y = (1, 2). Points higher up slide further right, so the whole grid leans: the same lean as the last step's rule. Watch the pink path: the dot is wherever its recipe ends.

Your turn: Change Y and watch every dot follow: vec2 Y = vec2(0.5, 1.0);

4. A matrix is those two arrows

A mat2 is exactly the two arrows from the last step, stored side by side as columns. Column 0 is where x goes (the red arrow), column 1 is where y goes (green). m * v means v.x * m[0] + v.y * m[1]: the same sum as before.

Writing it with four plain numbers is where everyone trips. GLSL fills a matrix column by column: mat2(a, b, c, d) means column 0 is (a, b) and column 1 is (c, d).

mat2(1.0, 0.0,   // column 0: x -> (1, 0)
     0.5, 1.0)   // column 1: y -> (0.5, 1)

So the matrix below tips the y axis over, just like the last step. If you'd read it row by row you'd expect the x axis to tip instead, and you'd be surprised.

Your turn: Make the x axis lean up instead, to (1, 0.5): return mat2(1.0, 0.5, 0.0, 1.0);

5. Working one out by hand

Do one on paper, the way the GPU does it, and it'll stick. A worked example first: mat2(2.0, 1.0, -1.0, 1.0) * vec2(3.0, 2.0). Read the columns: (2, 1) and (-1, 1). Then it's 3 lots of the first plus 2 lots of the second:

3 × ( 2, 1) = ( 6, 3)
2 × (-1, 1) = (-2, 2)
      added: ( 4, 5)

Now yours. Here m = mat2(1.0, 0.5, 0.0, 2.0) and v = (2, 1). One grid square is 1. The arrows draw the recipe (red: 2 steps of column 0, green: 1 step of column 1) and the blue dot is the GPU's answer.

Work it out before you read the dot's position off the grid, then type it into guess: the orange ring lands on the blue dot when you're right.

Your turn: Put your answer for m * v in guess (written like vec2(1.0, 2.0)).

6. Rows: each answer is a dot product

There's a second way to read the same matrix. Work out the x of m * v by hand: it's m[0].x * v.x + m[1].x * v.y. Those two numbers, the first entry of each column, make the first row.

So the answer's x is dot(row0, v), and its y is dot(row1, v). A dot product measures 'how far along this direction' (see Maths for shaders), so each row is a question the matrix asks about the point.

The stripes show the answer's x. They change as you move along the pink arrow, row0, and stay the same as you move across it, which is exactly what a dot product does.

Both readings are useful: columns tell you where things go, rows tell you how each answer is worked out. (GLSL's v * m, vector first, takes the dot products with the columns instead. That's the same as multiplying by the matrix flipped over its diagonal, transpose(m).)

Your turn: Work out the answer's x yourself: float qx = dot(row0, p);

7. Writing a matrix from a description

Now the other way round: you know what you want, and you need the matrix. One recipe always works. First, where should a step along x end up? Second, where should a step along y end up? Third, write those as the two columns.

Say you want everything turned a quarter turn anticlockwise. x points right, and should end up pointing up: (0, 1). y points up, and should end up pointing left: (-1, 0). So the matrix is mat2(0.0, 1.0, -1.0, 0.0). No sin or cos needed.

A few more, the same way:

mat2(2.0, 0.0, 0.0, 2.0)   // bigger
mat2(-1.0, 0.0, 0.0, 1.0)  // mirror
mat2(0.0, 1.0, 1.0, 0.0)   // swap x, y
mat2(-1.0, 0.0, 0.0, -1.0) // half turn

Your turn: Turn the grid a quarter turn: return mat2(0.0, 1.0, -1.0, 0.0); The red arrow points up and the green one left.

8. Stretch, squash, mirror, and the determinant

The simplest matrices only stretch the axes: x by one amount, y by another. mat2(1.5, 0.0, 0.0, 0.7) makes things 1.5 times wider and 0.7 times as tall. The shaded box is the square between the two arrows after the matrix.

How much does it scale areas? A 1 × 1 square becomes 1.5 × 0.7 = 1.05. That number is the determinant, determinant(m). For any 2D matrix it's m[0].x * m[1].y - m[1].x * m[0].y.

A negative number flips an axis: y = -0.7 turns everything upside down, like a reflection in a lake. The determinant goes negative too (1.5 × -0.7 = -1.05), and the box turns red. A negative determinant always means 'mirrored'.

At 0 the plane is squashed flat onto a line and you can't get back. That's why some matrices have no inverse.

Your turn: Flip it upside down: return mat2(1.5, 0.0, 0.0, -0.7);

9. Rotation, worked out

Turn the point (1, 0) by an angle a. It stays 1 away from the centre, so it lands on the circle of radius 1, at (cos a, sin a). That's the definition of cos and sin: the x and y of a point on that circle. (Angles are in radians: a quarter turn is about 1.571, a full turn about 6.283.)

Now any point (x, y) = x × (1, 0) + y × (0, 1). We know where (1, 0) goes: (cos a, sin a). (0, 1) is a quarter turn further round, so it goes to (-sin a, cos a). (A quarter turn sends (x, y) to (-y, x); try it on (1, 0).)

Add them up: x × (cos a, sin a) + y × (-sin a, cos a) gives

x' = x * c - y * s
y' = x * s + y * c

with c = cos a and s = sin a. Worked example: a quarter turn (c = 0, s = 1) sends (2, 1) to (2·0 − 1·1, 2·1 + 1·0) = (-1, 2).

Your turn: Write the rotation in rot: return vec2(v.x * c - v.y * s, v.x * s + v.y * c);

10. Shaders work backwards

Here's the twist that confuses everyone. A shader can't move a shape: each pixel can only ask 'what colour am I?'. So to draw an L that m has moved, each pixel works backwards: which point of the original L would m have sent here? If that point is in the L, colour the pixel.

Working backwards is the inverse, inverse(m), the matrix that undoes m. The code uses m * p instead, running the move forwards on the pixels, and the L comes out moved the opposite way: narrower instead of wider, leaning the wrong way. Compare it with the orange dots, which were moved properly.

That's why shader code so often seems backwards: making p bigger makes shapes smaller, adding to p moves shapes the other way, and rot(a) * p turns shapes by -a. You move the coordinates, and the picture moves the opposite way.

Your turn: Work backwards: vec2 q = inverse(m()) * p; The L's corners land on the orange dots.

11. Undoing a rotation for free

A rotation's columns are special: each is 1 long, and they're at right angles (their dot product is 0). Check: dot((c, s), (-s, c)) = -cs + sc = 0. Matrices like that are called orthonormal.

Now flip the matrix over its diagonal, transpose(m): its rows are the old columns. Multiplying transpose(m) * m takes the dot product of every column with every column: 1 with itself, 0 with the other. That's the 'do nothing' matrix (the identity). So the transpose undoes the rotation.

This matters because inverse() (last step) is real work, and transpose is free: it just reads the numbers in a different order. Careful, though: it only works for rotations. A stretch or a lean has no such luck.

The outline spins, because it's drawn at m * p. The solid box uses back.

Your turn: Undo the spin with the transpose: vec2 back = transpose(m) * (m * p); The solid box stops still.

12. Two matrices make one

A * B is a matrix too, so it's two columns, and you can work them out. Its first column is where a step along x ends up after B and then A: send B's first column through A. The same for the second column.

A is the quarter turn from Writing a matrix from a description, and B makes things twice as wide. Worked through:

B sends x to (2, 0)
A turns (2, 0) to (0, 2)
B sends y to (0, 1)
A turns (0, 1) to (-1, 0)

So A * B is mat2(0.0, 2.0, -1.0, 0.0): stretched, then turned, as one matrix. That's why a whole chain of moves costs a pixel just one multiply, if the chain is worked out once.

Your turn: Write A * B as four numbers: return mat2(0.0, 2.0, -1.0, 0.0); Nothing changes: the thick pink arrows are A * B, and your columns sit on top of them.

13. Order: read right to left

Two matrices can be multiplied into one: (A * B) * v is A * (B * v). B happens first, then A. So you read a chain of matrices from right to left, starting next to the point.

Here S stretches x by 1.8 and squashes y to 0.6, and R() turns. S * R() turns first, then stretches: the turning grid gets pulled sideways every frame, so its squares lean and wobble.

R() * S stretches first, then turns: the grid is stretched once and then spins as a solid thing. Same two matrices, a very different result. With matrices, A × B usually isn't B × A.

Your turn: Stretch first, then turn: mat2 m = R() * S;

14. Moving things: the extra 1

Look at the white dot: no 2D matrix can move it, because m × (0, 0) is always (0, 0). So 'move everything 0.3 to the right' isn't a matrix... unless we cheat.

The cheat: give every point a third number that's always 1, (x, y, 1), and use a mat3. Its third column gets multiplied by that 1, so it's simply added on: column 2 = (0.3, 0.1, 1) adds 0.3 to x and 0.1 to y.

(x, y, 1) ->
  x*col0 + y*col1 + 1*(0.3, 0.1, 1)

Directions use a 0 instead: (x, y, 0). They turn and stretch, but don't move, which is right: 'north' is still north after you walk somewhere. These are called homogeneous coordinates, and they're why 3D graphics uses mat4 (three coordinates plus the 1).

Your turn: Put the move in the third column: return mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.3, 0.1, 1.0);

15. Turning around any point

A rotation always turns around the origin. To turn around another point C (the pink dot), do it in three moves: slide C to the origin, turn, slide back.

With the extra-1 trick, all three are mat3s, so they multiply into one matrix. Reading right to left: translate(C) * rotate(time) * translate(-C).

Check it with C itself: translate(-C) sends C to (0, 0); the rotation leaves (0, 0) where it is; translate(C) sends it back to C. So C doesn't move, and everything else turns around it.

Your turn: Turn around C: mat3 m = translate(C) * rotate(time) * translate(-C);

16. 3D: three arrows

In 3D a point has three numbers: x to the right, y up, z into the screen. Everything from 2D carries over with one more arrow: a mat3 has three columns, where x, y and z go. Here they're drawn on the cube: x red, y green, z blue.

We're looking at the cube from a slight angle so it reads as 3D. The view is also just a matrix (viewTurn), and by the end of the course you'll be able to read it.

Change one column and the cube follows that arrow. Column 1 is where y goes: make it (0, 1.6, 0) and the cube is 1.6 times as tall. Make it (0.5, 1, 0) and it leans, just like the 2D grid did.

Your turn: Make the cube taller: change the middle column to vec3(0.0, 1.6, 0.0).

17. Turning about z: the 2D rotation again

Turning about the z axis (z points into the screen, so it's like turning a wheel that faces you) moves x and y exactly like the 2D rotation, and leaves z alone.

So the columns are the 2D ones with a 0 added, and z stays put:

x -> ( c, s, 0)
y -> (-s, c, 0)
z -> ( 0, 0, 1)

Watch the blue arrow when you're done: it doesn't move. Whatever a rotation turns about is the one direction that stays where it is. That direction is called the axis.

Your turn: Fill in the columns: return mat3(vec3(c, s, 0.0), vec3(-s, c, 0.0), vec3(0.0, 0.0, 1.0));

18. About x and y: one pattern, three axes

People memorise three rotation matrices and then wonder why the minus sign moves around in the y one. It doesn't really. There's one pattern, going round the cycle x → y → z → x.

Turning about z turns x towards y. Turning about x turns y towards z. Turning about y turns z towards x. Each is the 2D rotation applied to that pair, in that order:

about z: (x, y) turn, z stays
about x: (y, z) turn, x stays
about y: (z, x) turn, y stays

So for rotX, y goes to (0, c, s) (towards z) and z goes to (0, -s, c). For rotY the pair is (z, x), in that order, so z goes to (s, 0, c), and x goes to (c, 0, -s). The minus sign ends up in x's column because x is the second of the pair. That's the 'moved' sign.

Your turn: Write rotX from the pattern: return mat3(vec3(1.0, 0.0, 0.0), vec3(0.0, c, s), vec3(0.0, -s, c));

19. The shorthand: p.xz *= rot(a)

Open almost any raymarcher and you'll find lines like p.xz *= rot(a); with a 2D rot. It's a 3D turn written as a 2D one: p.xz is two of p's numbers, x and z, treated as a 2D point and turned. y isn't touched, so it turns about the y axis, like rotY.

The pair you pick sets the axis: the one left out is the one it turns about. .xz turns about y, .yz about x, .xy about z.

p.xz *= m means p.xz = p.xz * m, with the vector on the left, which multiplies by the transpose: for a rotation, the other way round. Nobody minds: if it spins the wrong way, flip the sign of the angle.

Here spin does it, and R() turns it into a matrix the way this course does everything: by sending each axis through it.

Your turn: Tumble it about x instead: v.yz *= rot(time);

20. In a raymarcher: turn the space, once a frame

In a raymarcher you don't turn the object, you turn the space you measure it in: map(p) turns p and then measures the box. It's the working-backwards idea again, in 3D.

map runs at every step of the march, for every pixel, and six more times for the normal: often hundreds of times per pixel. But rot(time * 0.5) comes out the same every time, because only time goes into it. That's the same sin and cos worked out hundreds of times a pixel, for nothing.

So work the matrix out once in main(), keep it in a global, and use that in map. glint's profiler (Alt G) suggests exactly this when it sees it. rot(0.4) can stay: it's a constant, which the compiler works out for you.

Only do this when nothing in the brackets changes during the march. rot(time + p.y) depends on p, so it has to stay where it is.

Your turn: Add mat2 spin; above map, set spin = rot(time * 0.5); at the start of main(), and use p.xz *= spin; in map. It looks the same, for less work.

21. Two turns: the world's axes or the cube's own

Put two rotations together and the order matters a lot. rotY(time) * rotX(0.6), read right to left: tip the cube 0.6 about x, then spin it about the world's up direction. The tip goes round and round, like a tilted plate on a turntable: the green arrow sweeps a cone.

rotX(0.6) * rotY(time): spin about the cube's own y first, then tip the whole spinning thing. Now it spins steadily around its own leaning green arrow, like a tilted spinning top.

Here's a handy trick: the same chain can be read the other way. Left to right, each rotation is about the cube's own axes, as already turned by the ones before. Right to left, every rotation is about the fixed world axes. Both readings are true, so use whichever makes your problem easier.

Your turn: Spin it about its own leaning axis: return rotX(0.6) * rotY(time);

22. Yaw, pitch, roll, and gimbal lock

A common way to aim something is three angles: yaw (turn left/right, about y), pitch (nod up/down, about x) and roll (tilt your head, about z). As one matrix: rotY(yaw) * rotX(pitch) * rotZ(roll). These are called Euler angles.

Here yaw and roll swing back and forth, with a small pitch. The cube wobbles in every direction.

Now set pitch to a quarter turn, 1.5708. The rotX turns the cube's own z axis to point along y, so roll now turns about y too: the same axis as yaw. Yaw and roll do the same thing, and the cube can no longer tip sideways at all, whatever you do with the three angles.

That's gimbal lock: one degree of freedom has gone. It's why cameras flip when you look straight up, and why animation tools use axis + angle or quaternions instead (next steps).

Your turn: Pitch a quarter turn: float pitch = 1.5708; and watch yaw and roll become the same motion.

23. Turning about any axis

To turn about any direction k (1 long; the pink line), split a point v into two parts. The part along k, k * dot(k, v), sits on the axis, so it doesn't move. The rest goes round in a circle around the axis.

In that circle, the rest of v and cross(k, v) act like the x and y of a 2D rotation (the cross product is the rest of v, turned a quarter turn about k). So the turned point is: the part on the axis + (rest of v) × cos + cross(k, v) × sin.

As matrices: outer(k) gives the part on the axis, the identity gives v itself, and a matrix K does the cross product (K * v == cross(k, v)). Gathered up, R = cos × I + sin × K + (1 − cos) × outer(k). That's Rodrigues' formula.

K is still all zeros, so the cube squashes instead of turning. Each column of K is the cross product of k with an axis: cross(k, (1,0,0)) = (0, k.z, −k.y), and so on.

Your turn: Fill in K: mat3 K = mat3(vec3(0.0, k.z, -k.y), vec3(-k.z, 0.0, k.x), vec3(k.y, -k.x, 0.0));

24. Pointing at something

Often you don't know the angles at all, you just want something to point at a target. A matrix is 'where the axes go', so choose them directly: the cube's z (blue) should point at the target, so f = normalize(target).

Then you need a right and an up that are at right angles to f and to each other. r = normalize(cross(worldUp, f)) is level and at right angles to f. Then u = cross(f, r) is at right angles to both.

Right now u is just the world's up, which isn't at right angles to f once the target moves up or down, so the cube gets bent out of shape. With the cross product all three are 1 long and at right angles, and three such arrows as columns always make a pure rotation. (This is a 'look-at' matrix. Cameras are built exactly this way.)

Your turn: Make up at right angles to the others: vec3 u = cross(f, r);

25. Blending between two rotations

To animate from one orientation A to another B, it's tempting to blend the matrices: A * (1 - t) + B * t. Watch what happens: the cube squashes flat in the middle.

Here's why, with numbers. A does nothing, so its x column is (1, 0, 0). B turns almost half way round, so its x column is about (-1, 0, 0). Halfway between those is (0, 0, 0). The blended matrix sends x nowhere, so the cube collapses. A blend of rotations isn't a rotation.

Blend the angle instead: rotY(3.0 * t) turns smoothly the whole way. In general, work out the turn that takes A to B (as an axis and an angle) and turn by t × that angle. That's what quaternion 'slerp' does in game engines.

Your turn: Blend the angle, not the matrix: return rotY(3.0 * t);

26. mat4: turn, move and perspective in one

Put it all together. Use the extra-1 trick in 3D: points become (x, y, z, 1) and matrices become mat4, with the move in the fourth column. Now turning and moving fit in a single matrix.

A whole scene is usually three of them, read right to left. model places the object in the world. view places the world in front of the camera (here: 5 units away). projection does the perspective. Together they're mvp, the uniform glint's vertex shaders get.

The projection matrix copies z into the fourth number (w). After it, you divide x and y by w, and dividing by distance is exactly what perspective is. The f / aspect and f entries are the zoom: f = 1 / tan(fov / 2), so a wider field of view (fov) shrinks everything.

(Real projection matrices also squeeze z into a range for the depth buffer, and OpenGL's z points the other way. The idea is the same.)

Your turn: Use a wider lens: float fov = 2.0;

Other courses: Basics · Medium · Advanced · Maths for shaders · Raymarching, step by step · Sound you can see · Noise from scratch · Colour and light · Passes and feedback · Skies and reflections · Vertex shaders, step by step · Raymarching 2: glow, fog and light · Raymarching 3: worlds · Raymarching 4: modelling, materials and motion · Fractals, step by step · Vertex shaders 2: lines, particles and moving meshes · Fractals 2: further in · Vertex shaders 3: living geometry · Post-processing · Surfaces: from vertex to fragment · Blur and glow