Volume 2: Continuous Mathematics · Part VII: Linear Algebra

Chapter 27. Matrices as Transformations

Most people first meet a matrix as a rectangular grid of numbers with a peculiar multiplication rule to memorise. That’s backwards. A matrix is a machine that moves space around: it can rotate it, stretch it, shear it, reflect it, or flatten it, and the grid of numbers is just a compact record of what the machine does. Once you see that, the strange multiplication rule becomes obvious (it’s "do one transformation, then another"), the inverse becomes "undo", the determinant becomes "how much does area change", and singular matrices become "transformations that squash space and can’t be reversed". This chapter builds every one of those ideas from pictures first, then turns them into procedures and code, and finishes in the places matrices earn their living: graphics pipelines and neural networks.

Where this chapter sits

You need: vectors, linear combinations, span and the dot product (Chapter 26); systems of linear equations and elimination (Chapter 6); sine and cosine on the unit circle (Chapter 13); the idea of a function as an input-to-output rule (Chapter 11). No calculus.

This chapter unlocks: eigenvectors, diagonalisation, PageRank, PCA and the SVD (Chapter 28); linear regression and least squares (Chapter 31); the Jacobian and the multivariable chain rule (Chapter 20); conditioning and numerical stability (Chapter 32); and the linear-algebra core of machine learning (Chapter 33).

Why this chapter matters. Whenever many outputs depend linearly on many inputs, a matrix is the bookkeeping: ingredients needed for a bakery’s orders, the joints of a robot arm, the pixels of a rotated photo, every vertex on a game screen, every layer of a neural network. Learn to read a matrix as a transformation and all of these become the same idea.

27.1. Transformations of space

27.1.1. The problem

A game needs to rotate a spaceship sprite by 30°. A photo editor needs to skew an image so a slanted building looks upright. A 3D engine must take every vertex of a model, place it in a world, look at it from a camera, and flatten the result onto a screen, 60 times a second, for millions of vertices. A neural network must turn a 768-number embedding into a 3072-number hidden representation.

Each of these is a function that takes vectors in and produces vectors out. We want a representation of such functions that is compact, fast to apply, easy to combine, and easy to reverse. For a very important class of them, the linear transformations, that representation is the matrix.

27.1.2. Intuition: watch the grid

The best way to understand a transformation of the plane is to apply it to everything at once and watch what happens to the coordinate grid. Here are six transformations applied to the grid, to an asymmetric letter F (so you can see flips and turns), and to the two standard basis vectors \(\mathbf{e}_1 = (1, 0)\) (green) and \(\mathbf{e}_2 = (0, 1)\) (red).

Six panels showing a grid and the letter F under identity, scaling, 30 degree rotation, shear, reflection in the y-axis, and projection onto the x-axis
Figure 241. Six linear transformations of the plane. Grey: the original grid. Blue: the transformed grid. The green and red arrows show where \(\mathbf{e}_1\) and \(\mathbf{e}_2\) land; the numbers above each panel are the matrix, written row by row.

Look at what all six have in common:

  • The origin stays put.

  • Straight grid lines stay straight (none of them bend into curves).

  • Parallel grid lines stay parallel, and evenly spaced lines stay evenly spaced.

These are the visual signatures of a linear transformation. A rotation keeps squares as squares; a scale stretches them into rectangles; a shear slants them into parallelograms; a reflection flips the F; a projection flattens the whole plane onto a line. But in every case, a regular grid becomes a regular grid (possibly a flattened one).

27.1.3. Why it works: the two rules of linearity

The pictures have a precise algebraic meaning. A function \(T\) from vectors to vectors is linear if, for all vectors \(\mathbf{u}, \mathbf{v}\) and scalars \(c\),

\[T(\mathbf{u} + \mathbf{v}) = T(\mathbf{u}) + T(\mathbf{v}) \qquad\text{and}\qquad T(c\,\mathbf{v}) = c\,T(\mathbf{v}).\]

In words: transforming a sum gives the sum of the transforms, and transforming a scaled vector gives the scaled transform. Tip-to-tail parallelograms map to tip-to-tail parallelograms. Taking \(c = 0\) shows \(T(\mathbf{0}) = \mathbf{0}\): the origin is fixed. And "evenly spaced lines stay evenly spaced" is the second rule applied to the multiples \(1\mathbf{v}, 2\mathbf{v}, 3\mathbf{v}, \ldots\).

Rotations, scalings, shears, reflections and projections through the origin are all linear. Some important transformations are not: translation (sliding everything by a fixed vector) moves the origin, so it fails the test. We’ll rescue translation with a clever trick in Section 27.11.

Linear transformation

A linear transformation (or linear map) \(T: \mathbb{R}^n \to \mathbb{R}^m\) is a function from \(n\)-dimensional vectors to \(m\)-dimensional vectors satisfying \(T(\mathbf{u} + \mathbf{v}) = T(\mathbf{u}) + T(\mathbf{v})\) and \(T(c\mathbf{v}) = cT(\mathbf{v})\). The arrow notation \(T: \mathbb{R}^n \to \mathbb{R}^m\) reads "T maps R-n to R-m": the domain is \(\mathbb{R}^n\), the codomain \(\mathbb{R}^m\). Geometrically: the origin is fixed, and grid lines stay straight, parallel and evenly spaced.

Change a matrix, watch the grid

Four sliders (or draggable number fields) set the entries of a \(2\times 2\) matrix \(\begin{bmatrix} a & b \\ c & d \end{bmatrix}\). The app shows the coordinate grid, the unit square, an asymmetric F and the two basis arrows, and animates them smoothly from the identity to the chosen transformation. The learner can also drag the tips of the green and red arrows directly, with the matrix entries updating to match (the columns are the arrow tips). Readouts show the determinant (with the unit square’s area highlighted) and flag when it reaches zero and the plane collapses to a line. Preset buttons: rotate, scale, shear, reflect, project. A "compose" mode applies two matrices in sequence and lets the learner swap their order.

27.2. The columns tell you everything

27.2.1. The problem

A linear transformation acts on infinitely many vectors. How can a finite list of numbers possibly describe it?

27.2.2. Intuition: follow the basis vectors

Every vector in the plane is a combination of the basis vectors: \((x, y) = x\,\mathbf{e}_1 + y\,\mathbf{e}_2\). Linearity says a transformation respects combinations. So

\[\begin{aligned} T(x, y) &= T(x\,\mathbf{e}_1 + y\,\mathbf{e}_2) \\ &= T(x\,\mathbf{e}_1) + T(y\,\mathbf{e}_2) &&\quad\text{(rule 1: sums)} \\ &= x\,T(\mathbf{e}_1) + y\,T(\mathbf{e}_2). &&\quad\text{(rule 2: scalars)} \end{aligned}\]

That’s the whole secret. Once you know where \(\mathbf{e}_1\) and \(\mathbf{e}_2\) land, you know where everything lands. A linear transformation of the plane is completely determined by two vectors, four numbers. Write those two landing spots side by side as columns, and you have the matrix:

\[A = \Big[\ T(\mathbf{e}_1)\ \ \Big|\ \ T(\mathbf{e}_2)\ \Big].\]
Before and after panels showing basis vectors moving to the columns of A and the vector (1,2) landing at (0,3)
Figure 242. The matrix \(A = \begin{bmatrix} 2 & -1 \\ 1 & 1 \end{bmatrix}\) sends \(\mathbf{e}_1\) to its first column \((2, 1)\) and \(\mathbf{e}_2\) to its second column \((-1, 1)\). The vector \(\mathbf{v} = (1, 2) = 1\mathbf{e}_1 + 2\mathbf{e}_2\) therefore lands at \(1(2, 1) + 2(-1, 1) = (0, 3)\).
Matrix

A matrix is a rectangular array of numbers. An \(m \times n\) matrix ("m by n") has \(m\) rows and \(n\) columns; rows first, always. The entry in row \(i\), column \(j\) is written \(a_{ij}\) (so \(a_{12}\) is row 1, column 2). As a transformation, an \(m\times n\) matrix takes \(n\)-dimensional vectors to \(m\)-dimensional vectors: column \(j\) is where the \(j\)-th basis vector lands. A square matrix has \(m = n\) and maps a space to itself. The word is Latin for "womb" (the thing from which something grows), chosen by James Sylvester in 1850.

27.2.3. Matrix–vector multiplication: two views

Applying a matrix to a vector is written \(A\mathbf{x}\), and from the derivation above we already know what it must be: a linear combination of the columns, weighted by the entries of \(\mathbf{x}\).

\[\begin{bmatrix} a & b \\ c & d \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} = x \begin{bmatrix} a \\ c \end{bmatrix} + y \begin{bmatrix} b \\ d \end{bmatrix} = \begin{bmatrix} ax + by \\ cx + dy \end{bmatrix}.\]

Now read the final result row by row. The top entry \(ax + by\) is the dot product of the first row \((a, b)\) with \(\mathbf{x}\); the bottom entry is the dot product of the second row with \(\mathbf{x}\). So there are two equally correct ways to compute \(A\mathbf{x}\):

  • Column view: \(A\mathbf{x}\) is a combination of the columns of \(A\). This is the geometric view: "where do the basis vectors go, and how much of each do I take?"

  • Row view: entry \(i\) of \(A\mathbf{x}\) is (row \(i\) of \(A\)) \(\cdot\ \mathbf{x}\). This is the computational view, and it’s what you do by hand. It’s also what the semantic search in Chapter 26 did: stacking document vectors as rows of \(D\) made \(D\mathbf{q}\) the list of all document–query dot products.

Example 148. Procedure — multiply a matrix by a vector

Input: an \(m\times n\) matrix \(A\) and a vector \(\mathbf{x}\) with \(n\) entries.

Steps:

  1. Check that the number of columns of \(A\) equals the length of \(\mathbf{x}\). If not, the product is undefined.

  2. For each row \(i = 1, \ldots, m\): multiply each entry \(a_{ij}\) by \(x_j\) and add, giving \((A\mathbf{x})_i = \sum_{j=1}^n a_{ij} x_j\).

  3. (Equivalently: add up \(x_1 \times\) column 1, \(x_2 \times\) column 2, …​, \(x_n \times\) column \(n\).)

Output: the vector \(A\mathbf{x}\) with \(m\) entries. Cost: \(mn\) multiplications.

27.2.4. Worked example

Compute \(A\mathbf{v}\) for \(A = \begin{bmatrix} 2 & -1 \\ 1 & 1 \end{bmatrix}\) and \(\mathbf{v} = (1, 2)\), both ways.

\[\begin{aligned} \text{Row view: } A\mathbf{v} &= \begin{bmatrix} (2)(1) + (-1)(2) \\ (1)(1) + (1)(2) \end{bmatrix} = \begin{bmatrix} 0 \\ 3 \end{bmatrix}, \\[4pt] \text{Column view: } A\mathbf{v} &= 1\begin{bmatrix} 2 \\ 1 \end{bmatrix} + 2\begin{bmatrix} -1 \\ 1 \end{bmatrix} = \begin{bmatrix} 2 - 2 \\ 1 + 2 \end{bmatrix} = \begin{bmatrix} 0 \\ 3 \end{bmatrix}. \end{aligned}\]

Same answer, of course, and it matches the diagram. In code the two views are two loop orders over the same arithmetic:

def matvec_rows(A, x):
    """Each output entry is (row of A) . x"""
    return [sum(a * xi for a, xi in zip(row, x)) for row in A]

def matvec_cols(A, x):
    """Output is x[0]*(column 0) + x[1]*(column 1) + ..."""
    m, n = len(A), len(A[0])
    out = [0] * m
    for j in range(n):              # for each column ...
        for i in range(m):          # ... add x[j] times that column
            out[i] += x[j] * A[i][j]
    return out

A = [[2, -1],
     [1,  1]]
x = [1, 2]
print(matvec_rows(A, x), matvec_cols(A, x))
[0, 3] [0, 3]

27.2.5. Reading a matrix at a glance

The column view lets you read a matrix geometrically. Faced with \(\begin{bmatrix} 1 & 0.8 \\ 0 & 1 \end{bmatrix}\), don’t see four numbers: see "\(\mathbf{e}_1\) stays at \((1, 0)\); \(\mathbf{e}_2\) tips over to \((0.8, 1)\)". That’s a horizontal shear: points slide sideways by an amount proportional to their height. Faced with \(\begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix}\): "\(\mathbf{e}_1\) stays, \(\mathbf{e}_2\) is crushed to zero", a projection onto the x-axis.

27.2.6. Where you’d use this: many outputs from many inputs

A matrix–vector product is the right tool whenever several totals each depend on the same list of inputs.

  • Everyday: a bakery’s shopping list. A cake needs 200 g flour, 150 g sugar and 3 eggs; a batch of cookies needs 300 g flour, 100 g sugar and 1 egg. Put each product’s recipe in a column. An order of 4 cakes and 2 batches is the vector \((4, 2)\), and

    \[\underbrace{\begin{bmatrix} 200 & 300 \\ 150 & 100 \\ 3 & 1 \end{bmatrix}}_{\text{recipes}} \begin{bmatrix} 4 \\ 2 \end{bmatrix} = 4\begin{bmatrix} 200 \\ 150 \\ 3 \end{bmatrix} + 2\begin{bmatrix} 300 \\ 100 \\ 1 \end{bmatrix} = \begin{bmatrix} 1400 \\ 800 \\ 14 \end{bmatrix}\]

    is the shopping list: 1400 g flour, 800 g sugar, 14 eggs. That’s the column view in action: 4 copies of the cake column plus 2 of the cookie column. Restaurant stock systems, manufacturing "bill of materials" software and diet planners all do this.

  • Science and engineering: economists' input–output models (Leontief won the 1973 Nobel prize for them) are this calculation for a whole economy, with a column per industry saying what it consumes to make one unit. In electronics, the currents in a resistor network are linear in the source voltages, so a circuit simulator stores the network as a matrix.

  • Computing: the row view is a batch of dot products, so scoring one user against 10,000 items in a recommender, or one query against every document in a search index, is a single matrix–vector product.

Rows and columns are not interchangeable

The columns of \(A\) are the images of the basis vectors, not the rows. Writing the landing spot of \(\mathbf{e}_1\) as the first row by mistake gives you the transpose (Section 27.10), which is a different transformation unless the matrix is symmetric. A rotation written this way rotates the wrong way. Some graphics APIs and textbooks use row vectors multiplied on the left (\(\mathbf{x}A\) instead of \(A\mathbf{x}\)), in which case everything is transposed. DirectX conventionally uses row vectors and OpenGL column vectors; when porting code between them, this is the number-one source of bugs.

US curriculum

Matrix arithmetic (adding, multiplying, determinants and inverses of \(2\times 2\) matrices, solving systems with matrices) appears in many Algebra II and Precalculus courses, often as a computational unit (Common Core N-VM.6–12, "+" standards). Matrices as transformations of the plane are touched on in some Precalculus courses but are mostly taught in a first college course in Linear Algebra, typically taken in the first or second year of a STEM degree.

Because columns are landing spots, you can build the matrix for any linear transformation by asking where \(\mathbf{e}_1\) and \(\mathbf{e}_2\) go.

27.3.1. Scaling

Stretch horizontally by \(s_x\) and vertically by \(s_y\): \(\mathbf{e}_1 \mapsto (s_x, 0)\), \(\mathbf{e}_2 \mapsto (0, s_y)\).

\[S = \begin{bmatrix} s_x & 0 \\ 0 & s_y \end{bmatrix}.\]

A matrix that’s zero off the main diagonal (top-left to bottom-right) is a diagonal matrix, and it just scales each axis independently. Diagonal matrices are the simplest matrices there are, and much of Chapter 28 is about turning other matrices into diagonal ones.

27.3.2. Rotation, derived from trigonometry

Rotate the plane anticlockwise by angle \(\theta\) about the origin. Where does \(\mathbf{e}_1 = (1, 0)\) go? It’s a unit vector, so it stays on the unit circle, now at angle \(\theta\): by the definition of sine and cosine (Chapter 13), it lands at \((\cos\theta, \sin\theta)\).

Where does \(\mathbf{e}_2 = (0, 1)\) go? It starts at angle \(90^\circ\) and ends at \(90^\circ + \theta\), so it lands at \((\cos(90^\circ + \theta), \sin(90^\circ + \theta)) = (-\sin\theta, \cos\theta)\). (You can also see this from the diagram: the rotated \(\mathbf{e}_2\) is the rotated \(\mathbf{e}_1\) turned a further quarter-turn, and a quarter-turn sends \((p, q)\) to \((-q, p)\).)

Unit circle with e1 and e2 rotated by theta, showing their new coordinates
Figure 243. Rotating the basis vectors by \(\theta\): \(\mathbf{e}_1\) lands at \((\cos\theta, \sin\theta)\) and \(\mathbf{e}_2\) at \((-\sin\theta, \cos\theta)\). These are the columns of the rotation matrix.

Put the landing spots in as columns:

\[R_\theta = \begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix}, \qquad R_\theta \begin{bmatrix} x \\ y \end{bmatrix} = \begin{bmatrix} x\cos\theta - y\sin\theta \\ x\sin\theta + y\cos\theta \end{bmatrix}.\]

This is the formula behind every 2D rotation in every game engine, and it falls out of nothing more than "columns are where the basis vectors go" plus the unit circle. Worked check: rotate \((3, 4)\) by \(90^\circ\). With \(\cos 90^\circ = 0\), \(\sin 90^\circ = 1\): \((3\cdot 0 - 4\cdot 1,\ 3\cdot 1 + 4\cdot 0) = (-4, 3)\). Its length is still 5, and \((3, 4)\cdot(-4, 3) = -12 + 12 = 0\), so it’s perpendicular to the original. ✓

27.3.3. Shear, reflection, projection

  • Horizontal shear by factor \(k\): \(\begin{bmatrix} 1 & k \\ 0 & 1 \end{bmatrix}\). Points at height \(y\) slide sideways by \(ky\). Italic fonts are (roughly) a shear of upright ones.

  • Reflection in the y-axis: \(\begin{bmatrix} -1 & 0 \\ 0 & 1 \end{bmatrix}\); in the line \(y = x\): \(\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}\) (it swaps coordinates).

  • Projection onto the x-axis: \(\begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix}\). More generally, projection onto the line through a unit vector \(\hat{\mathbf{u}} = (u_1, u_2)\) sends \(\mathbf{x}\) to \((\mathbf{x}\cdot\hat{\mathbf{u}})\hat{\mathbf{u}}\) (Chapter 26); applying that to \(\mathbf{e}_1\) and \(\mathbf{e}_2\) gives the matrix \(\begin{bmatrix} u_1^2 & u_1 u_2 \\ u_1 u_2 & u_2^2 \end{bmatrix}\).

27.3.4. Where you’d use this

  • Everyday: a phone’s photo editor implements "rotate 90°", "flip horizontal" (the reflection \(\begin{bmatrix} -1 & 0 \\ 0 & 1 \end{bmatrix}\), which is also what a selfie camera’s mirror preview does) and "straighten" (a small rotation) with exactly these matrices, applied to pixel coordinates.

  • Science and engineering: robots and sensors. A robot vacuum facing 30° anticlockwise from the room’s x-axis sees an obstacle 2 m straight ahead, at \((2, 0)\) in its own frame. In room directions that’s \(R_{30^\circ}(2, 0) = (2\cos 30^\circ, 2\sin 30^\circ) \approx (1.73, 1.00)\) m from the robot. Every robot, drone and phone (turning gyroscope readings into "which way is up") rotates measurements between frames like this. Crystallographers describe the symmetries of a crystal as a small set of rotation and reflection matrices.

  • Computing: sprite and camera rotation in games, italic and oblique fonts (a shear), the "flatten 3D to 2D" projection in every renderer, and data augmentation in machine learning, where training images are randomly rotated, flipped and sheared so a classifier learns that a tilted cat is still a cat.

Non-square matrices change dimension

A \(2\times 3\) matrix has 3 columns (images of \(\mathbf{e}_1, \mathbf{e}_2, \mathbf{e}_3\) in 3D), each with 2 entries (they land in 2D). So it maps \(\mathbb{R}^3 \to \mathbb{R}^2\), for example by dropping the depth of a 3D point to draw it on paper: \(\begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \end{bmatrix}\) keeps \(x\), \(y\) and discards \(z\). An \(m\times n\) matrix eats \(n\)-vectors and produces \(m\)-vectors. A neural-network layer from 768 to 3072 dimensions is a \(3072\times 768\) matrix.

27.4. Exercises: matrices as transformations

  1. (Recognition) Describe in words what \(\begin{bmatrix} 3 & 0 \\ 0 & 3 \end{bmatrix}\), \(\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}\) and \(\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}\) do to the plane.

  2. (Application) Write the matrix that sends \(\mathbf{e}_1\) to \((1, 2)\) and \(\mathbf{e}_2\) to \((3, -1)\), and use it to transform \((2, 1)\) by both the row and column methods.

  3. (Application) Find the matrix that rotates by \(60^\circ\), and apply it to \((2, 0)\).

  4. (Problem solving) Is \(T(x, y) = (x + 1, y)\) linear? Is \(T(x, y) = (y, x^2)\)? Justify each with the linearity rules.

Answers
  1. Uniform scaling by 3 (everything three times as far from the origin); anticlockwise rotation by \(90^\circ\) (\(\mathbf{e}_1 \mapsto \mathbf{e}_2\), \(\mathbf{e}_2 \mapsto -\mathbf{e}_1\)); reflection in the x-axis (flip vertically).

  2. \(A = \begin{bmatrix} 1 & 3 \\ 2 & -1 \end{bmatrix}\). Rows: \((1\cdot 2 + 3\cdot 1,\ 2\cdot 2 + (-1)\cdot 1) = (5, 3)\). Columns: \(2(1, 2) + 1(3, -1) = (2 + 3, 4 - 1) = (5, 3)\).

  3. \(\cos 60^\circ = \tfrac{1}{2}\), \(\sin 60^\circ = \tfrac{\sqrt{3}}{2}\): \(R = \begin{bmatrix} 1/2 & -\sqrt{3}/2 \\ \sqrt{3}/2 & 1/2 \end{bmatrix}\). \(R(2, 0) = (1, \sqrt{3}) \approx (1, 1.732)\), length still 2.

  4. \((x + 1, y)\) is not linear: \(T(0, 0) = (1, 0) \neq \mathbf{0}\) (it’s a translation). \((y, x^2)\) is not linear: \(T(2\cdot(1, 0)) = T(2, 0) = (0, 4)\) but \(2T(1, 0) = 2(0, 1) = (0, 2)\).

27.5. Matrix multiplication is composition

27.5.1. The problem

A game rotates a sprite by \(90^\circ\) and then shears it. With a million vertices, you’d rather not apply two matrices to every vertex; you’d like one matrix that does both. What is it? And does the order matter?

27.5.2. Intuition: follow the basis vectors again

Let \(B\) be the first transformation and \(A\) the second. The combined transformation sends \(\mathbf{x}\) to \(A(B\mathbf{x})\). Doing one linear transformation after another is still linear (grid lines stay straight through both steps), so it has a matrix, and we find it as always: by tracking the basis vectors.

  • \(B\) sends \(\mathbf{e}_1\) to \(B\)'s first column, call it \(\mathbf{b}_1\). Then \(A\) sends that to \(A\mathbf{b}_1\).

  • Likewise \(\mathbf{e}_2\) ends up at \(A\mathbf{b}_2\).

So the combined matrix, written \(AB\), has columns \(A\mathbf{b}_1\) and \(A\mathbf{b}_2\):

\[AB = A\Big[\ \mathbf{b}_1\ \Big|\ \mathbf{b}_2\ \Big] = \Big[\ A\mathbf{b}_1\ \Big|\ A\mathbf{b}_2\ \Big].\]

Each column of the product is \(A\) times the corresponding column of \(B\). That’s the definition of matrix multiplication, and it is forced by the requirement that \((AB)\mathbf{x} = A(B\mathbf{x})\).

Now apply the row view of matrix–vector multiplication to each \(A\mathbf{b}_j\): entry \(i\) of column \(j\) is (row \(i\) of \(A\)) \(\cdot\) (column \(j\) of \(B\)). That’s the familiar "row times column" rule:

\[(AB)_{ij} = \sum_{k} a_{ik}\, b_{kj}.\]
Read products right to left

In \(AB\mathbf{x}\), the transformation nearest the vector acts first. \(AB\) means "do \(B\), then \(A\)", exactly like function composition \(f(g(x))\) or \((f \circ g)(x)\), where \(g\) happens first (Chapter 11). Graphics code that builds \(M = T R S\) (translate · rotate · scale) applies the scale first and the translation last.

27.5.3. Order matters: matrix multiplication is not commutative

Let \(R = \begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}\) (rotate \(90^\circ\)) and \(S = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}\) (shear). Compute both orders.

\(SR\) (rotate first, then shear). Columns of \(R\) are \((0, 1)\) and \((-1, 0)\). Apply \(S\) to each:

\[\begin{aligned} S\begin{bmatrix} 0 \\ 1 \end{bmatrix} &= \begin{bmatrix} 1\cdot 0 + 1\cdot 1 \\ 0\cdot 0 + 1\cdot 1 \end{bmatrix} = \begin{bmatrix} 1 \\ 1 \end{bmatrix}, & S\begin{bmatrix} -1 \\ 0 \end{bmatrix} &= \begin{bmatrix} -1 + 0 \\ 0 + 0 \end{bmatrix} = \begin{bmatrix} -1 \\ 0 \end{bmatrix}, & SR &= \begin{bmatrix} 1 & -1 \\ 1 & 0 \end{bmatrix}. \end{aligned}\]

\(RS\) (shear first, then rotate). Columns of \(S\) are \((1, 0)\) and \((1, 1)\):

\[\begin{aligned} R\begin{bmatrix} 1 \\ 0 \end{bmatrix} &= \begin{bmatrix} 0 \\ 1 \end{bmatrix}, & R\begin{bmatrix} 1 \\ 1 \end{bmatrix} &= \begin{bmatrix} 0 - 1 \\ 1 + 0 \end{bmatrix} = \begin{bmatrix} -1 \\ 1 \end{bmatrix}, & RS &= \begin{bmatrix} 0 & -1 \\ 1 & 1 \end{bmatrix}. \end{aligned}\]

\(SR \neq RS\). The picture makes it obvious:

Three panels: the original F, the F rotated then sheared, and the F sheared then rotated, which differ
Figure 244. The same two transformations in different orders give different results. Matrix multiplication is not commutative.

Think of everyday actions: "put on socks, then shoes" differs from "shoes, then socks". Some pairs do commute (two rotations about the same point; two scalings; anything with the identity), but you may never assume it.

Example 149. Procedure — multiply two matrices

Input: an \(m\times n\) matrix \(A\) and an \(n\times p\) matrix \(B\).

Steps:

  1. Check the inner dimensions match: columns of \(A\) (\(n\)) = rows of \(B\) (\(n\)). The result will be \(m\times p\) (the outer dimensions).

  2. For each row \(i\) of \(A\) and each column \(j\) of \(B\): compute the dot product \(c_{ij} = \sum_{k=1}^{n} a_{ik} b_{kj}\).

  3. Place \(c_{ij}\) in row \(i\), column \(j\) of the result.

Output: \(C = AB\), which represents "apply \(B\), then \(A\)". Cost: \(m \cdot n \cdot p\) multiplications.

27.5.4. Worked example

Compute \(\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}\begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix}\). Try it: Step through this product.

\[\begin{aligned} c_{11} &= (\text{row 1})\cdot(\text{col 1}) = 1\cdot 5 + 2\cdot 7 = 19, & c_{12} &= (\text{row 1})\cdot(\text{col 2}) = 1\cdot 6 + 2\cdot 8 = 22, \\ c_{21} &= (\text{row 2})\cdot(\text{col 1}) = 3\cdot 5 + 4\cdot 7 = 43, & c_{22} &= (\text{row 2})\cdot(\text{col 2}) = 3\cdot 6 + 4\cdot 8 = 50, \end{aligned}\]

so the product is \(\begin{bmatrix} 19 & 22 \\ 43 & 50 \end{bmatrix}\). (In the other order you’d get \(\begin{bmatrix} 23 & 34 \\ 31 & 46 \end{bmatrix}\): different again.) Try it: Try the other order.

27.5.5. Identity, associativity, and powers

The identity matrix \(I\) has 1s on the diagonal and 0s elsewhere. It sends every basis vector to itself, so it’s the "do nothing" transformation: \(AI = IA = A\). It plays the role of 1 in ordinary multiplication.

Matrix multiplication is associative: \((AB)C = A(BC)\). Both sides mean "do \(C\), then \(B\), then \(A\)", so they must be the same transformation. This is why a graphics engine can pre-multiply a chain of a dozen transformations into a single matrix once per frame and then apply that one matrix to every vertex. It’s also why \(A^n\) (\(A\) multiplied by itself \(n\) times, "apply \(A\) \(n\) times") is unambiguous, which Chapter 28 exploits heavily.

Identity matrix and matrix product
  • The identity matrix \(I_n\) is the \(n\times n\) matrix with 1s on the main diagonal and 0s elsewhere. \(I\mathbf{x} = \mathbf{x}\) for every \(\mathbf{x}\).

  • The product \(AB\) is defined when (columns of \(A\)) = (rows of \(B\)), and \((AB)_{ij}\) = (row \(i\) of \(A\)) \(\cdot\) (column \(j\) of \(B\)). It represents applying \(B\) then \(A\).

  • Laws: associative \((AB)C = A(BC)\); distributive \(A(B + C) = AB + AC\); not commutative in general.

27.5.6. Where you’d use this

  • Everyday: price a recipe once, not every time. Continue the bakery: flour costs £1.20/kg, sugar £2/kg and eggs 25p each, so the price row vector is \(\mathbf{p} = (0.0012, 0.002, 0.25)\) (per gram, per gram, per egg). The product \(\mathbf{p}R\) (a \(1\times 3\) times a \(3\times 2\)) gives the ingredient cost of each product: \(0.24 + 0.30 + 0.75 = 1.29\), so £1.29 per cake, and \(0.36 + 0.20 + 0.25 = 0.81\), so £0.81 per batch of cookies. Associativity says \((\mathbf{p}R)\mathbf{q} = \mathbf{p}(R\mathbf{q})\): costing the order of 4 cakes and 2 batches either way gives \(4(1.29) + 2(0.81) = 6.78\), that is £6.78.

  • Science and engineering: a robot arm’s hand position is found by multiplying one transformation matrix per joint (shoulder, elbow, wrist), which is called forward kinematics. In optics, each lens and gap in a camera or telescope is a \(2\times 2\) "ray transfer" matrix, and the whole instrument is their product.

  • Computing: a game object inside a vehicle inside a world has its matrix computed as a product down the scene graph; animation systems compose bone transformations the same way; and Chapter 28 uses powers \(A^n\) to step a Markov chain or a Fibonacci recurrence many steps at once.

Rotations add, and trigonometry falls out

Rotating by \(\beta\) and then by \(\alpha\) is obviously rotating by \(\alpha + \beta\). So \(R_\alpha R_\beta = R_{\alpha + \beta}\). Multiply out the left side:

\[\begin{bmatrix} \cos\alpha & -\sin\alpha \\ \sin\alpha & \cos\alpha \end{bmatrix} \begin{bmatrix} \cos\beta & -\sin\beta \\ \sin\beta & \cos\beta \end{bmatrix} = \begin{bmatrix} \cos\alpha\cos\beta - \sin\alpha\sin\beta & \cdots \\ \sin\alpha\cos\beta + \cos\alpha\sin\beta & \cdots \end{bmatrix}.\]

Compare with the first column of \(R_{\alpha+\beta}\), which is \((\cos(\alpha + \beta), \sin(\alpha + \beta))\). You’ve just derived both angle-addition formulas from Chapter 13, the ones that took a page of geometry to prove at school, from one matrix multiplication.

27.5.7. Implementing it, and what it costs

import numpy as np

def matmul(A, B):
    """Product of an m x n and an n x p matrix (lists of rows)."""
    m, n, p = len(A), len(B), len(B[0])
    assert len(A[0]) == n, "inner dimensions must match"
    C = [[0] * p for _ in range(m)]
    for i in range(m):              # each row of A
        for j in range(p):          # each column of B
            for k in range(n):      # dot product of row i and column j
                C[i][j] += A[i][k] * B[k][j]
    return C

R = [[0, -1], [1, 0]]               # rotate 90 degrees
S = [[1, 1], [0, 1]]                # shear
print(matmul(S, R))                 # rotate first, then shear
print(matmul(R, S))                 # shear first, then rotate

# NumPy agrees, and is enormously faster for big matrices.
print(np.array(S) @ np.array(R))
[[1, -1], [1, 0]]
[[0, -1], [1, 1]]
[[ 1 -1]
 [ 1  0]]

Three nested loops of length \(n\) mean \(n^3\) multiplications for two \(n\times n\) matrices: \(O(n^3)\). Doubling \(n\) multiplies the work by 8. For \(n = 1000\) that’s a billion multiply-adds: a minute or more in pure Python, a few tens of milliseconds in NumPy.

Computer-science connection: why matrix multiplication is the most optimised code on Earth

NumPy’s @ calls a BLAS library (OpenBLAS, Intel MKL, Apple Accelerate) whose GEMM ("general matrix multiply") routine is hand-tuned in assembly. It still does \(O(n^3)\) arithmetic, but it reorganises the loops into blocks that fit in the CPU caches, uses SIMD instructions, and runs on every core, reaching a large fraction of the hardware’s peak speed. The naive triple loop spends most of its time waiting for memory. On a GPU, the same operation runs on thousands of cores, and modern GPUs have dedicated tensor cores that do nothing but small matrix multiplies. Training a large neural network is, to a first approximation, a few trillion trillion multiply-adds inside matrix multiplications.

Can you beat \(n^3\)? Yes, in theory. Volker Strassen showed in 1969 that two \(2\times 2\) block matrices can be multiplied with 7 block multiplications instead of 8, giving \(O(n^{\log_2 7}) \approx O(n^{2.81})\). Research has pushed the exponent below 2.372, but those algorithms only win for astronomically large matrices. Strassen itself is occasionally used in practice; the rest are "galactic algorithms". The connection to Chapter 12: the exponent \(\log_2 7\) comes from a divide-and-conquer recurrence.

27.6. The determinant: how much space changes

27.6.1. The problem

When a matrix transforms the plane, the unit square (the square spanned by \(\mathbf{e}_1\) and \(\mathbf{e}_2\)) becomes a parallelogram spanned by the two columns. How does its area change? And can we tell from the numbers alone whether the transformation flips space over, or flattens it completely?

27.6.2. Intuition

Because grid lines stay parallel and evenly spaced, every grid square becomes a copy of the same parallelogram. So every region’s area is multiplied by the same factor: the area of the transformed unit square. That factor, with a sign attached to record whether the transformation flips orientation, is the determinant, \(\det A\).

Three panels: a shear-and-stretch with determinant 3, a shrink with determinant one quarter, and a swap of axes with determinant minus one showing a mirrored F
Figure 245. The determinant is the factor by which areas are multiplied (blue parallelogram versus grey unit square). A negative determinant means orientation is reversed: the F is mirrored.

27.6.3. Why it works: deriving the formula

Let \(A = \begin{bmatrix} a & b \\ c & d \end{bmatrix}\) with all entries positive and the columns \((a, c)\) and \((b, d)\) arranged as in the first panel above. The parallelogram fits in a rectangle of width \(a + b\) and height \(c + d\). The parts of the rectangle outside the parallelogram are two triangles of area \(\tfrac{1}{2}ac\), two of area \(\tfrac{1}{2}bd\), and two small rectangles of area \(bc\). Subtract them:

\[\begin{aligned} \text{area} &= (a + b)(c + d) - 2\cdot\tfrac{1}{2}ac - 2\cdot\tfrac{1}{2}bd - 2bc \\ &= ac + ad + bc + bd - ac - bd - 2bc &&\quad\text{(expand)} \\ &= ad - bc. &&\quad\text{(collect)} \end{aligned}\]

(Sketching that rectangle and its six pieces on paper is well worth the minute it takes.) In general,

\[\det\begin{bmatrix} a & b \\ c & d \end{bmatrix} = ad - bc,\]

and the sign comes out right automatically: swapping the columns (which mirrors the picture) gives \(bc - ad\), the negative. Notice that for the cross-product-style "2D cross" \(a_1 b_2 - a_2 b_1\) from Chapter 26, this is the same expression: its sign said whether the second vector was anticlockwise of the first, which is exactly orientation.

Determinant

The determinant of a square matrix, written \(\det A\) or \(|A|\), is the signed factor by which the transformation scales area (2D) or volume (3D and up).

  • \(|\det A|\) = scale factor for area/volume.

  • \(\det A < 0\): orientation is reversed (a mirror image).

  • \(\det A = 0\): space is flattened into a lower dimension; the matrix is singular.

  • For \(2\times 2\): \(\det\begin{bmatrix} a & b \\ c & d \end{bmatrix} = ad - bc\).

  • \(\det(AB) = \det A \cdot \det B\) (scale factors multiply when you compose) and \(\det I = 1\).

27.6.4. Worked example

For the three panels above:

\[\begin{aligned} \det\begin{bmatrix} 2 & 1 \\ 0 & 1.5 \end{bmatrix} &= 2(1.5) - 1(0) = 3, \\ \det\begin{bmatrix} 0.5 & 0 \\ 0 & 0.5 \end{bmatrix} &= 0.25 - 0 = 0.25, \\ \det\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix} &= 0 - 1 = -1. \end{aligned}\]

A rotation has \(\det R_\theta = \cos^2\theta + \sin^2\theta = 1\): it neither grows nor shrinks area and doesn’t mirror. A shear \(\begin{bmatrix} 1 & k \\ 0 & 1 \end{bmatrix}\) has determinant 1 too: it slants squares into parallelograms of the same base and height. Scaling a 2D shape by 3 in both directions multiplies its area by \(\det(3I) = 9\), not 3.

27.6.5. Three dimensions, briefly

For a \(3\times 3\) matrix, the determinant is the signed volume of the parallelepiped (slanted box) spanned by the three columns. One way to compute it is cofactor expansion along the first row:

\[\det\begin{bmatrix} a_1 & a_2 & a_3 \\ b_1 & b_2 & b_3 \\ c_1 & c_2 & c_3 \end{bmatrix} = a_1(b_2 c_3 - b_3 c_2) - a_2(b_1 c_3 - b_3 c_1) + a_3(b_1 c_2 - b_2 c_1).\]

Each bracket is a \(2\times 2\) determinant of what’s left after deleting row 1 and the entry’s column; signs alternate \(+, -, +\). If you put \(\mathbf{i}, \mathbf{j}, \mathbf{k}\) in the first row and two vectors in the others, this formula produces exactly the cross product of Chapter 26, which is the mnemonic promised there. For anything larger than \(3\times 3\), don’t expand by hand (the work grows like \(n!\)); computers use elimination, as described next.

27.6.6. Where you’d use this

  • Everyday and surveying: area from coordinates. A triangular plot of land has corners \((0, 0)\), \((40, 10)\) and \((15, 30)\) in metres. Its two edge vectors from the first corner are the columns of a matrix, and the triangle is half the parallelogram they span:

    \[\text{area} = \tfrac{1}{2}\left|\det\begin{bmatrix} 40 & 15 \\ 10 & 30 \end{bmatrix}\right| = \tfrac{1}{2}\,|40\cdot 30 - 15\cdot 10| = \tfrac{1}{2}(1200 - 150) = 525 \text{ m}^2.\]

    Splitting any polygon into triangles this way gives the shoelace formula, which surveyors, GIS software and mapping apps use to compute the area of a field or a building footprint from its corner coordinates.

  • Science: when you change variables in a multiple integral (to polar coordinates, say), the determinant of the Jacobian matrix is the local area-scaling factor (Chapter 20). In mechanics, a negative determinant is how you spot that a coordinate change has mirrored space (switched right- and left-handed axes).

  • Computing: the sign of a \(2\times 2\) determinant is the standard orientation test in computational geometry: is point \(C\) to the left or right of the line from \(A\) to \(B\)? Convex-hull algorithms, polygon triangulation, and "did these two line segments cross?" checks in games and CAD all reduce to it.

The determinant is not a measure of "how invertible"

\(\det A = 0\) exactly means singular. But a small determinant does not mean "nearly singular". The matrix \(0.1\,I_{100}\) (shrink every one of 100 axes by 10) has determinant \(10^{-100}\), yet it’s perfectly well-behaved and trivially inverted. And a matrix with determinant 1 can be extremely close to singular, like \(\begin{bmatrix} 10^{6} & 0 \\ 0 & 10^{-6} \end{bmatrix}\). To judge how close a matrix is to singular, numerical analysts use the condition number (Chapter 32), which compares the largest and smallest stretching factors. And in floating point, a computed determinant of \(10^{-17}\) is almost always "zero plus rounding error", never test det == 0.

27.7. Inverses and singular matrices

27.7.1. The problem

A camera transformation maps world coordinates to screen coordinates. The player clicks a pixel: which point in the world did they click? An image has been deliberately rotated and sheared; how do you put it back? Both ask: can a transformation be undone, and if so, by what matrix?

27.7.2. Intuition: undo, if nothing was lost

The inverse of \(A\), written \(A^{-1}\), is the transformation that puts everything back: \(A^{-1}A = I\), and also \(AA^{-1} = I\). For a rotation by \(\theta\) it’s rotation by \(-\theta\). For a scaling by 2 it’s scaling by \(\tfrac{1}{2}\). For a shear by \(k\) it’s the shear by \(-k\).

But some transformations cannot be undone. Projection onto the x-axis sends \((3, 5)\) and \((3, -2)\) both to \((3, 0)\). Given only \((3, 0)\), there’s no way to know where it came from: information has been destroyed. This happens exactly when the transformation squashes space into a lower dimension, which is exactly when the determinant is zero.

A cloud of points before and after a singular matrix, which squashes them all onto the line y equals x over 2
Figure 246. A singular matrix flattens the plane. Every point lands on one line, and many different points land on the same spot, so no inverse can exist.

In that example the second column \((2, 1)\) is exactly twice the first column \((1, 0.5)\). Both basis vectors land on the same line, so their combinations (everything) land on that line. Singular means the columns are linearly dependent (Chapter 26): they fail to span the whole space.

Invertible and singular

A square matrix \(A\) is invertible (or non-singular) if there’s a matrix \(A^{-1}\) with \(AA^{-1} = A^{-1}A = I\). Otherwise it is singular. For a square matrix, all of these are equivalent: \(A\) is invertible; \(\det A \neq 0\); the columns are linearly independent; the columns span the whole space; \(A\mathbf{x} = \mathbf{b}\) has exactly one solution for every \(\mathbf{b}\); \(A\mathbf{x} = \mathbf{0}\) only for \(\mathbf{x} = \mathbf{0}\). Non-square matrices never have a two-sided inverse.

27.7.3. Deriving the \(2\times 2\) inverse

Undoing \(A\) means: given an output \((p, q)\), find the input \((x, y)\) with

\[\begin{aligned} ax + by &= p \\ cx + dy &= q. \end{aligned}\]

That’s a linear system, so solve it by elimination (Chapter 6). To eliminate \(y\), multiply the first equation by \(d\) and the second by \(b\), and subtract:

\[\begin{array}{rcl} adx + bdy &=& dp \\ bcx + bdy &=& bq \\ \hline (ad - bc)\,x &=& dp - bq. \end{array}\]

To eliminate \(x\), multiply the first by \(c\), the second by \(a\), and subtract the first from the second: \((ad - bc)\,y = aq - cp\). If \(ad - bc \neq 0\), divide:

\[\begin{bmatrix} x \\ y \end{bmatrix} = \frac{1}{ad - bc}\begin{bmatrix} dp - bq \\ -cp + aq \end{bmatrix} = \frac{1}{ad - bc}\begin{bmatrix} d & -b \\ -c & a \end{bmatrix}\begin{bmatrix} p \\ q \end{bmatrix}.\]

The matrix taking \((p, q)\) back to \((x, y)\) is the inverse:

\[\boxed{\ \begin{bmatrix} a & b \\ c & d \end{bmatrix}^{-1} = \frac{1}{ad - bc}\begin{bmatrix} d & -b \\ -c & a \end{bmatrix}\ }\]

Swap the diagonal, negate the off-diagonal, divide by the determinant. And there’s the determinant, appearing on its own: if it’s zero, you’d divide by zero, which is the algebra’s way of saying "this can’t be undone".

Example 150. Procedure — inverting a \(2\times 2\) matrix

Input: \(A = \begin{bmatrix} a & b \\ c & d \end{bmatrix}\).

Steps:

  1. Compute \(\det A = ad - bc\). If it is 0 (in floating point: tiny relative to the entries), stop: \(A\) is singular.

  2. Swap \(a\) and \(d\); change the signs of \(b\) and \(c\).

  3. Multiply every entry by \(1/\det A\).

  4. Check: \(AA^{-1}\) should be \(I\).

Output: \(A^{-1}\).

27.7.4. Worked example

Invert \(A = \begin{bmatrix} 3 & 1 \\ 5 & 2 \end{bmatrix}\) and use it to solve \(3x + y = 5\), \(5x + 2y = 9\). Try it: Check this inverse; Solve the system.

\[\begin{aligned} \det A &= 3\cdot 2 - 1\cdot 5 = 1, \\ A^{-1} &= \frac{1}{1}\begin{bmatrix} 2 & -1 \\ -5 & 3 \end{bmatrix}, \\ \text{check: } AA^{-1} &= \begin{bmatrix} 3\cdot 2 + 1\cdot(-5) & 3\cdot(-1) + 1\cdot 3 \\ 5\cdot 2 + 2\cdot(-5) & 5\cdot(-1) + 2\cdot 3 \end{bmatrix} = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}, \quad\checkmark \\ \begin{bmatrix} x \\ y \end{bmatrix} &= A^{-1}\begin{bmatrix} 5 \\ 9 \end{bmatrix} = \begin{bmatrix} 2\cdot 5 - 1\cdot 9 \\ -5\cdot 5 + 3\cdot 9 \end{bmatrix} = \begin{bmatrix} 1 \\ 2 \end{bmatrix}. \end{aligned}\]

Check in the original equations: \(3 + 2 = 5\) ✓, \(5 + 4 = 9\) ✓.

def inverse_2x2(A, tol=1e-12):
    (a, b), (c, d) = A
    det = a * d - b * c
    if abs(det) < tol:
        raise ValueError("matrix is singular (or nearly so): no inverse")
    return [[ d / det, -b / det],
            [-c / det,  a / det]]

A = [[3, 1], [5, 2]]
print(inverse_2x2(A))
[[2.0, -1.0], [-5.0, 3.0]]

27.7.5. Where you’d use this

  • Everyday: recovering hidden quantities. A café sold 120 drinks yesterday, coffees at £3 and teas at £2, and took £310. With \(x\) coffees and \(y\) teas, \(\begin{bmatrix} 1 & 1 \\ 3 & 2 \end{bmatrix}\begin{bmatrix} x \\ y \end{bmatrix} = \begin{bmatrix} 120 \\ 310 \end{bmatrix}\). The determinant is \(2 - 3 = -1\), so the inverse is \(\frac{1}{-1}\begin{bmatrix} 2 & -1 \\ -3 & 1 \end{bmatrix} = \begin{bmatrix} -2 & 1 \\ 3 & -1 \end{bmatrix}\), giving \(x = -240 + 310 = 70\) coffees and \(y = 360 - 310 = 50\) teas. (Check: \(70 + 50 = 120\), \(210 + 100 = 310\).) Try it: Solve the café problem.

  • Science and engineering: GPS receivers, circuit simulators and structural-engineering software all solve linear systems, from a handful of unknowns to millions. Undoing a known distortion is an inverse too: a scanner that knows how its optics warp the page applies the inverse map to straighten the image.

  • Computing: when you click on a 3D scene, the game must work out which point in the world you clicked. The renderer maps world to screen with a matrix \(M\); picking applies \(M^{-1}\) to the click. Because rotations are orthogonal, their inverse is just the transpose (Section 27.10), which is why engines keep rotation, scale and translation separate: each is trivial to invert on its own.

Socks and shoes

The inverse of a product reverses the order: \((AB)^{-1} = B^{-1}A^{-1}\). To undo "socks, then shoes" you remove shoes first, then socks. Check: \((AB)(B^{-1}A^{-1}) = A(BB^{-1})A^{-1} = AIA^{-1} = AA^{-1} = I\). Also \((A^{-1})^{-1} = A\) and \(\det(A^{-1}) = 1/\det A\) (if \(A\) multiplies areas by 3, undoing it divides them by 3).

27.8. Solving \(A\mathbf{x} = \mathbf{b}\)

27.8.1. The problem, recast

Any system of linear equations can be written as one matrix equation. The system

\[\begin{aligned} 2x + y - z &= 1 \\ x + 3y + 2z &= 13 \\ x &= 2 \end{aligned} \qquad\text{is}\qquad \underbrace{\begin{bmatrix} 2 & 1 & -1 \\ 1 & 3 & 2 \\ 1 & 0 & 0 \end{bmatrix}}_{A} \underbrace{\begin{bmatrix} x \\ y \\ z \end{bmatrix}}_{\mathbf{x}} = \underbrace{\begin{bmatrix} 1 \\ 13 \\ 2 \end{bmatrix}}_{\mathbf{b}}.\]

Check by the row view: row 1 of \(A\) dotted with \(\mathbf{x}\) is \(2x + y - z\), the first left-hand side. This compact form is how systems are written in every linear-algebra paper and every numerical library.

27.8.2. Two pictures of the same equation

Chapter 6 taught you the row picture: each equation is a line (or plane), and the solution is where they all meet. Matrices add the column picture: \(A\mathbf{x}\) is a combination of the columns of \(A\), so solving \(A\mathbf{x} = \mathbf{b}\) asks

How much of each column do I need to build \(\mathbf{b}\)?

and, as a transformation: which input does \(A\) send to \(\mathbf{b}\)? That gives a clean geometric account of the three cases from Chapter 6:

  • \(A\) invertible: \(A\) reaches every point exactly once, so there’s exactly one solution, \(\mathbf{x} = A^{-1}\mathbf{b}\).

  • \(A\) singular and \(\mathbf{b}\) off the squashed image (not in the span of the columns): no input reaches \(\mathbf{b}\); no solution.

  • \(A\) singular and \(\mathbf{b}\) on the image: many inputs were squashed onto \(\mathbf{b}\); infinitely many solutions.

Two panels. Left: the lines 2x minus y equals 0 and x plus y equals 3 crossing at the point (1, 2). Right: arrow (2,1) followed by two copies of (-1,1), ending at b equals (0,3)
Figure 247. Two pictures of the system \(2x - y = 0\), \(x + y = 3\), which is \(A\mathbf{x} = \mathbf{b}\) with \(A = \begin{bmatrix} 2 & -1 \\ 1 & 1 \end{bmatrix}\) and \(\mathbf{b} = (0, 3)\). Left: each row is a line, and the solution \((1, 2)\) is where they cross. Right: the same answer read as "1 of column 1 plus 2 of column 2 builds \(\mathbf{b}\)", exactly the landing of \(\mathbf{v} = (1, 2)\) in the columns diagram earlier.

27.8.3. Rank: how many dimensions survive

The rank of a matrix is the dimension of its output: the number of independent directions the columns span. A \(3\times 3\) matrix of rank 3 fills all of space (invertible); rank 2 flattens space onto a plane; rank 1 crushes it onto a line; rank 0 is the zero matrix. The singular example above has rank 1. Rank is the honest measure of how much information a transformation preserves, and it returns in Chapter 28 as the key to compressing data with low-rank approximations.

Rank

The rank of a matrix is the number of linearly independent columns (equivalently, of independent rows: the two counts always agree), which is the dimension of the set of all outputs \(A\mathbf{x}\) (the column space or image). An \(n\times n\) matrix is invertible exactly when its rank is \(n\) (full rank). The input directions squashed to zero form the null space (or kernel); its dimension is \(n - \text{rank}\).

27.8.4. Choosing a method

import numpy as np

A = np.array([[2.0, 1.0, -1.0],
              [1.0, 3.0,  2.0],
              [1.0, 0.0,  0.0]])
b = np.array([1.0, 13.0, 2.0])
x = np.linalg.solve(A, b)
print(x, np.allclose(A @ x, b))

print(round(np.linalg.det(A), 6), np.linalg.matrix_rank(A))
S = np.array([[1.0, 2.0], [0.5, 1.0]])
print(np.linalg.det(S), np.linalg.matrix_rank(S))
[2. 1. 4.] True
5.0 3
0.0 1
  • By hand, 2×2: use the inverse formula or elimination; both are quick.

  • By hand, 3×3: use elimination (Chapter 6). The inverse is much more work.

  • In code, any size: call np.linalg.solve(A, b). It runs Gaussian elimination (as an LU factorisation) in \(O(n^3)\).

  • Many right-hand sides with the same \(A\): factorise once (scipy.linalg.lu_factor), then each solve is only \(O(n^2)\).

Don’t compute the inverse to solve a system

\(\mathbf{x} = A^{-1}\mathbf{b}\) is the right way to think, and the wrong way to compute. np.linalg.inv(A) @ b does roughly three times the work of np.linalg.solve(A, b) and is less accurate in floating point. Numerical analysts have a saying: "if you’re computing an inverse, you’re probably doing something wrong". Keep \(A^{-1}\) in your formulas and solve in your code.

27.9. Exercises: products, determinants, inverses

  1. (Recognition) Which products are defined, and what shape are they: \((2\times 3)(3\times 4)\), \((3\times 2)(3\times 2)\), \((1\times 5)(5\times 1)\), \((5\times 1)(1\times 5)\)?

  2. (Application) Compute \(\begin{bmatrix} 2 & 0 \\ 1 & 3 \end{bmatrix}\begin{bmatrix} 1 & -1 \\ 4 & 2 \end{bmatrix}\).

  3. (Application) Find the determinant and inverse of \(\begin{bmatrix} 4 & 7 \\ 2 & 6 \end{bmatrix}\).

  4. (Application) For which value of \(k\) is \(\begin{bmatrix} 2 & k \\ 3 & 6 \end{bmatrix}\) singular? Describe its image for that \(k\).

  5. (Problem solving) A transformation doubles all areas and preserves orientation; another triples areas and reverses orientation. What is the determinant of "the first, then the second"? Of its inverse?

Answers
  1. \(2\times 4\); undefined (inner 2 ≠ 3); \(1\times 1\) (a single number: it’s a dot product); \(5\times 5\) (an outer product, every entry of one times every entry of the other).

  2. Row 1: \((2\cdot 1 + 0\cdot 4,\ 2\cdot(-1) + 0\cdot 2) = (2, -2)\). Row 2: \((1\cdot 1 + 3\cdot 4,\ 1\cdot(-1) + 3\cdot 2) = (13, 5)\). Result \(\begin{bmatrix} 2 & -2 \\ 13 & 5 \end{bmatrix}\).

  3. \(\det = 24 - 14 = 10\). Inverse \(\frac{1}{10}\begin{bmatrix} 6 & -7 \\ -2 & 4 \end{bmatrix} = \begin{bmatrix} 0.6 & -0.7 \\ -0.2 & 0.4 \end{bmatrix}\). Check the top-left of the product: \(4(0.6) + 7(-0.2) = 2.4 - 1.4 = 1\). ✓

  4. \(\det = 12 - 3k = 0\) gives \(k = 4\). Then the columns \((2, 3)\) and \((4, 6)\) are parallel (the second is twice the first), so the image is the line through the origin in direction \((2, 3)\), i.e. \(y = \tfrac{3}{2}x\).

  5. Determinants multiply: \(2 \times (-3) = -6\). The inverse has determinant \(-\tfrac{1}{6}\).

27.10. The transpose

27.10.1. Definition and meaning

The transpose \(A^\mathsf{T}\) of a matrix flips it across its main diagonal: rows become columns. If \(A\) is \(m\times n\), then \(A^\mathsf{T}\) is \(n\times m\), with \((A^\mathsf{T})_{ij} = a_{ji}\).

\[\begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix}^\mathsf{T} = \begin{bmatrix} 1 & 4 \\ 2 & 5 \\ 3 & 6 \end{bmatrix}.\]

The transpose has less obvious geometry than the other operations, but it’s everywhere in practice, for three reasons.

1. It turns dot products into matrix products. Treat a column vector as an \(n\times 1\) matrix. Then \(\mathbf{a}^\mathsf{T}\) is \(1\times n\), and \(\mathbf{a}^\mathsf{T}\mathbf{b}\) is \((1\times n)(n\times 1) = 1\times 1\): a single number, which is exactly \(\mathbf{a}\cdot\mathbf{b}\). That’s why papers write \(\mathbf{q}^\mathsf{T}\mathbf{d}\) for the dot product, and \(\mathbf{x}^\mathsf{T}A\mathbf{x}\) for "transform \(\mathbf{x}\), then dot it with itself".

2. It reverses products: \((AB)^\mathsf{T} = B^\mathsf{T}A^\mathsf{T}\), the same socks-and-shoes reversal as the inverse.

3. For rotations, it is the inverse. The columns of a rotation matrix are perpendicular unit vectors (\(\mathbf{e}_1\) and \(\mathbf{e}_2\) rotated together). In \(R^\mathsf{T}R\), entry \((i, j)\) is (column \(i\)) \(\cdot\) (column \(j\)), which is 1 when \(i = j\) and 0 otherwise. So \(R^\mathsf{T}R = I\) and \(R^{-1} = R^\mathsf{T}\): inverting a rotation costs nothing. Matrices with orthonormal columns are called orthogonal matrices; they are the rigid motions (rotations and reflections) that preserve all lengths and angles.

Transpose, symmetric, orthogonal
  • Transpose \(A^\mathsf{T}\): rows and columns swapped. \((A^\mathsf{T})^\mathsf{T} = A\), \((AB)^\mathsf{T} = B^\mathsf{T}A^\mathsf{T}\), \(\mathbf{a}\cdot\mathbf{b} = \mathbf{a}^\mathsf{T}\mathbf{b}\). Other notations: \(A^T\), \(A'\) (statistics, MATLAB), A.T (NumPy).

  • Symmetric matrix: \(A^\mathsf{T} = A\) (a mirror image across the diagonal). Covariance matrices and distance matrices are symmetric; Chapter 28 shows they have especially beautiful eigenvectors.

  • Orthogonal matrix: \(Q^\mathsf{T}Q = I\), so \(Q^{-1} = Q^\mathsf{T}\). Its columns are orthonormal; it preserves lengths and angles; \(\det Q = \pm 1\).

27.11. Translation and homogeneous coordinates

27.11.1. The problem

Rotating a sprite about its own centre, rather than about the origin, requires moving it to the origin, rotating, and moving it back. But moving (translation) isn’t linear: it doesn’t fix the origin, so no \(2\times 2\) matrix can do it. That spoils the plan of combining every transformation into one matrix.

27.11.2. The trick: add a dimension

Write the 2D point \((x, y)\) as the 3D vector \((x, y, 1)\). Now consider the \(3\times 3\) matrix

\[T = \begin{bmatrix} 1 & 0 & t_x \\ 0 & 1 & t_y \\ 0 & 0 & 1 \end{bmatrix}, \qquad T\begin{bmatrix} x \\ y \\ 1 \end{bmatrix} = \begin{bmatrix} x + t_x \\ y + t_y \\ 1 \end{bmatrix}.\]

The constant 1 in the third slot, multiplied by the third column, smuggles in the shift. In three dimensions, translation is a shear that slides the plane \(z = 1\) sideways, and shears are linear. Rotations and scalings embed by putting their \(2\times 2\) matrix in the top-left corner with a 1 in the bottom-right. Now everything, including translation, is a matrix, and any sequence of moves collapses into one matrix by multiplication.

This also encodes the point/vector distinction from Chapter 26. A point gets a final coordinate 1 and is translated. A direction vector gets a final coordinate 0, so translation leaves it alone, which is correct: moving a spaceship doesn’t change which way "forward" is. Subtracting two points (1 − 1 = 0) gives a vector, automatically.

Homogeneous coordinates

Homogeneous coordinates represent a 2D point \((x, y)\) as \((x, y, 1)\) and a 3D point \((x, y, z)\) as \((x, y, z, 1)\), so that translations, rotations, scalings and (in 3D graphics) perspective projections are all matrix multiplications: \(3\times 3\) matrices for 2D graphics, \(4\times 4\) for 3D. Directions use a final coordinate of 0. More generally \((X, Y, W)\) with \(W \neq 0\) represents the point \((X/W, Y/W)\); dividing by \(W\) is what makes perspective work.

A house shape, its rotation about the origin, and the rotated shape translated up and to the right
Figure 248. A house rotated 40° about the origin (orange), then translated by \((4, 1)\) (blue), using a single \(3\times 3\) homogeneous matrix \(TR\).

27.11.3. Worked example: rotate about a point

Rotate the points \((2, 1)\), \((3, 1)\), \((3, 2)\) by \(90^\circ\) about the point \((2, 1)\). Plan (read right to left): translate by \((-2, -1)\) so the pivot is at the origin, rotate, translate back. Try it: Rotate then translate the house; Rotate about a point.

\[M = T(2, 1)\;R_{90^\circ}\;T(-2, -1).\]

By hand for \((3, 2)\): subtract the pivot, \((1, 1)\); rotate by \(90^\circ\), \((p, q) \mapsto (-q, p)\), giving \((-1, 1)\); add the pivot back, \((1, 2)\). In code, all three points at once, stored as columns:

import numpy as np

def translate(tx, ty):
    return np.array([[1, 0, tx],
                     [0, 1, ty],
                     [0, 0, 1.0]])

def rotate(deg):
    t = np.radians(deg)
    return np.array([[np.cos(t), -np.sin(t), 0],
                     [np.sin(t),  np.cos(t), 0],
                     [0,          0,         1.0]])

# Rotate 90 degrees about the point (2, 1), not about the origin:
# move (2, 1) to the origin, rotate, move back. Read right to left.
M = translate(2, 1) @ rotate(90) @ translate(-2, -1)

corners = np.array([[2, 3, 3],      # x-coordinates of three points
                    [1, 1, 2],      # y-coordinates
                    [1, 1, 1]])     # the extra 1s: "these are points"
print(np.round(M @ corners, 10))
[[2. 2. 1.]
 [1. 2. 2.]
 [1. 1. 1.]]

The pivot \((2, 1)\) stays fixed, \((3, 1)\) swings up to \((2, 2)\), and \((3, 2)\) goes to \((1, 2)\), matching the hand calculation. (The np.round hides rounding noise like 6e-17 from \(\cos 90^\circ\) in floating point.)

Computer-science connection: the graphics pipeline

Every vertex in a 3D game passes through a chain of \(4\times 4\) homogeneous matrices:

Flow from object space through model, view and projection matrices to clip space, then perspective divide and viewport to screen pixels
  • The model matrix \(M\) places an object in the world (scale, rotate, translate).

  • The view matrix \(V\) moves the world so the camera sits at the origin looking down an axis. It’s the inverse of the camera’s own placement matrix: moving the camera left is the same as moving the world right.

  • The projection matrix \(P\) sets up perspective. It copies depth into the fourth (\(w\)) coordinate, and the GPU then divides \(x\) and \(y\) by \(w\): distant things (large \(w\)) shrink. That division is the one non-linear step, and homogeneous coordinates make it a single cheap operation at the end.

The engine multiplies \(PVM\) once per object per frame (associativity at work), and the GPU’s vertex shader applies that single matrix to every vertex: gl_Position = mvp * vec4(position, 1.0);. Normal vectors, which are directions, use 0 as the fourth coordinate (and, if the model matrix contains non-uniform scaling, need the inverse-transpose matrix to stay perpendicular to their surfaces).

Image transforms work in reverse. To rotate a photo, you don’t push each source pixel forward (that leaves gaps); you loop over every output pixel, apply the inverse matrix to find where it came from in the source, and interpolate between the nearest source pixels. Image libraries' "affine warp" functions take exactly a \(2\times 3\) or \(3\times 3\) matrix.

Why "homogeneous"?

Homogeneous coordinates were introduced by August Möbius in 1827 for projective geometry, the mathematics of perspective drawing that Renaissance painters had worked out by eye. In projective geometry, parallel railway lines really do meet at the horizon: the meeting point is a "point at infinity" with final coordinate 0. The name refers to the equations becoming homogeneous (every term of the same degree). It took 140 years for the idea to find its killer application, when Lawrence Roberts used it for computer graphics at MIT in the 1960s.

27.12. Neural network layers: matrix multiply plus a bend

27.12.1. The problem

A neural network takes a vector in (an image’s pixels, a sentence’s embedding) and produces a vector out (class probabilities, a next-word distribution). In between are layers. What does a layer actually compute?

27.12.2. A layer is a matrix, then a nonlinearity

A dense (fully connected) layer from \(n\) inputs to \(m\) outputs computes

\[\mathbf{h} = \sigma(W\mathbf{x} + \mathbf{b}),\]

where \(W\) is an \(m\times n\) weight matrix, \(\mathbf{b}\) an \(m\)-vector of biases, and \(\sigma\) a simple function applied to each entry separately, such as the ReLU \(\sigma(z) = \max(0, z)\). Read it with this chapter’s eyes:

  • \(W\mathbf{x}\) is a linear transformation from \(\mathbb{R}^n\) to \(\mathbb{R}^m\). By the row view, output \(i\) is the dot product of row \(i\) of \(W\) with \(\mathbf{x}\): each output "neuron" measures how much the input aligns with a learned direction, like the similarity scores in Chapter 26.

  • \(+\,\mathbf{b}\) is a translation (so the whole thing is affine, exactly what homogeneous coordinates handle).

  • \(\sigma\) bends space. Without it, stacking layers would be pointless: \(W_2(W_1\mathbf{x}) = (W_2 W_1)\mathbf{x}\), a single matrix, because a composition of linear maps is linear. The nonlinearity is what lets deep networks represent curved decision boundaries.

Training adjusts the entries of \(W\) and \(\mathbf{b}\) using gradients (Chapter 20). But running a network, called inference, is almost entirely matrix multiplication.

import numpy as np

def relu(z):
    return np.maximum(0, z)

rng = np.random.default_rng(0)
W1, b1 = rng.standard_normal((4, 3)), np.zeros(4)   # layer 1: R^3 -> R^4
W2, b2 = rng.standard_normal((2, 4)), np.zeros(2)   # layer 2: R^4 -> R^2

x = np.array([1.0, 0.5, -2.0])       # one input with 3 features
h = relu(W1 @ x + b1)                # hidden layer: 4 numbers
y = W2 @ h + b2                      # output: 2 numbers
print(h.shape, y.shape)

X = rng.standard_normal((32, 3))     # a batch of 32 inputs, one per row
H = relu(X @ W1.T + b1)              # all 32 at once: one matrix multiply
print(H.shape)
(4,) (2,)
(32, 4)

The last two lines show the trick that makes GPUs so effective: instead of 32 matrix–vector products, stack the inputs as rows of a matrix \(X\) and do one matrix–matrix product. Note the transpose: with inputs as rows, \(X W_1^\mathsf{T}\) has row \(i\) equal to \((W_1\mathbf{x}_i)^\mathsf{T}\). Mismatched shapes in exactly this spot are the most common bug in hand-written ML code; when NumPy complains, write the shapes of every factor down and check the inner dimensions.

Computer-science connection: counting the cost of a model

A layer mapping 768 dimensions to 3072 has a \(3072 \times 768\) weight matrix: about 2.4 million numbers, and 2.4 million multiply-adds per input vector. A transformer language model is stacks of such layers. Rule of thumb: generating one token with a model of \(P\) parameters costs about \(2P\) floating-point operations, because each weight takes part in one multiply and one add. Knowing that "inference is mostly matrix–vector products, training mostly matrix–matrix products" explains most of the hardware story: memory bandwidth limits the former, raw arithmetic the latter.

Neurons as directions

A 2D dataset of two interleaved classes (for example two spirals). The learner picks a \(2\times 2\) matrix and bias for one layer and watches the data transform; then toggles ReLU on and off and sees how the bend folds the plane. A second layer follows. The app shows that without ReLU, two layers collapse to one matrix (it displays \(W_2 W_1\)), while with ReLU the classes can be pulled apart.

27.13. Exercises: transpose, homogeneous coordinates, layers

  1. (Recognition) If \(A\) is \(3\times 5\), what shape is \(A^\mathsf{T}A\)? \(AA^\mathsf{T}\)? Are they symmetric?

  2. (Application) Write the \(3\times 3\) homogeneous matrix that scales by 2 about the origin and then translates by \((1, -3)\), and apply it to the point \((4, 5)\) and to the direction \((4, 5)\).

  3. (Application) Verify that \(R_{30^\circ}^\mathsf{T}R_{30^\circ} = I\) by multiplying out with \(c = \cos 30^\circ\), \(s = \sin 30^\circ\).

  4. (Problem solving) A network layer computes \(W_2(W_1\mathbf{x})\) with no nonlinearity, where \(W_1\) is \(2\times 100\) and \(W_2\) is \(100\times 2\). What is the largest possible rank of the combined matrix, and what does that say about this "network"?

Answers
  1. \(A^\mathsf{T}A\) is \((5\times 3)(3\times 5) = 5\times 5\); \(AA^\mathsf{T}\) is \(3\times 3\). Both are symmetric: \((A^\mathsf{T}A)^\mathsf{T} = A^\mathsf{T}(A^\mathsf{T})^\mathsf{T} = A^\mathsf{T}A\).

  2. \(M = \begin{bmatrix} 2 & 0 & 1 \\ 0 & 2 & -3 \\ 0 & 0 & 1 \end{bmatrix}\). Point: \(M(4, 5, 1) = (8 + 1, 10 - 3, 1) = (9, 7, 1)\), i.e. \((9, 7)\). Direction: \(M(4, 5, 0) = (8, 10, 0)\): scaled but not translated.

  3. \(R^\mathsf{T}R = \begin{bmatrix} c & s \\ -s & c \end{bmatrix}\begin{bmatrix} c & -s \\ s & c \end{bmatrix} = \begin{bmatrix} c^2 + s^2 & -cs + sc \\ -sc + cs & s^2 + c^2 \end{bmatrix} = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}\), using \(\sin^2 + \cos^2 = 1\).

  4. \(W_2 W_1\) is \(100\times 100\), but every input first passes through the 2-dimensional bottleneck \(W_1\mathbf{x}\), so the rank is at most 2. The 100-dimensional output always lies in a plane. Without a nonlinearity, depth adds nothing: the two layers are one rank-≤2 linear map.

27.14. Summary

  • A matrix is a linear transformation: it fixes the origin and keeps grid lines straight, parallel and evenly spaced. It can rotate, scale, shear, reflect and project. Try it: Scale then translate (exercise).

  • Columns are where the basis vectors land. \(A\mathbf{x}\) is a combination of the columns (geometric view) or a list of row-dot-\(\mathbf{x}\) values (computational view).

  • Matrix multiplication is composition: \(AB\) means "\(B\) then \(A\)". It’s associative but not commutative, and costs \(O(n^3)\) naively.

  • The rotation matrix \(\begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix}\) comes straight from the unit circle; composing rotations yields the angle-addition formulas.

  • The determinant is the signed area/volume scale factor; \(ad - bc\) for \(2\times 2\). Zero means singular: space is squashed, information lost, no inverse.

  • The inverse undoes a transformation; for \(2\times 2\), swap the diagonal, negate the off-diagonal, divide by \(\det\). To solve \(A\mathbf{x} = \mathbf{b}\) in code, use solve, not inv.

  • Rank counts the dimensions that survive. The transpose turns dot products into matrix products and inverts rotations.

  • Homogeneous coordinates make translation (and perspective) a matrix, so graphics pipelines are chains of \(4\times 4\) matrices. Neural network layers are matrix multiplies with a nonlinearity between them.

27.15. Interactive tools

Browser tools on the companion website that go with this chapter. Each example link in the chapter opens one of them with that example already set up.

27.16. Mastery check

  1. Write down the matrix that sends \(\mathbf{e}_1 \mapsto (0, 2)\) and \(\mathbf{e}_2 \mapsto (-1, 0)\). Describe the transformation in words, and give its determinant.

  2. Compute \(\begin{bmatrix} 1 & 2 \\ 0 & -1 \end{bmatrix}\begin{bmatrix} 3 \\ 4 \end{bmatrix}\) by both the row view and the column view.

  3. Let \(A = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}\) and \(B = \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}\). Compute \(AB\) and \(BA\), and describe geometrically what multiplying by \(B\) on each side does.

  4. Find \(A^{-1}\) for \(A = \begin{bmatrix} 2 & 3 \\ 1 & 2 \end{bmatrix}\) and use it to solve \(2x + 3y = 7\), \(x + 2y = 4\).

  5. Explain, using the picture of a transformation, why a matrix with determinant 0 cannot have an inverse.

  6. Derive the matrix for an anticlockwise rotation by \(\theta\) from scratch, and use it to rotate \((1, 1)\) by \(45^\circ\).

  7. Give the \(3\times 3\) homogeneous matrix that translates by \((5, -2)\), and explain why no \(2\times 2\) matrix can do the same job.

  8. A layer computes \(\operatorname{ReLU}(W\mathbf{x} + \mathbf{b})\) with \(\mathbf{x} \in \mathbb{R}^{512}\) and output in \(\mathbb{R}^{128}\). What are the shapes of \(W\) and \(\mathbf{b}\), and how many multiplications does \(W\mathbf{x}\) need?

Decision rule: All correct without hesitation → move on to Chapter 28. Stuck on 1–2 or 6 → reread Section 27.2 and Section 27.3. Stuck on 3 → reread Section 27.5. Stuck on 4–5 → reread Section 27.6 and Section 27.7. Stuck on 7–8 → reread Section 27.11 and Section 27.12.

Mastery check answers
  1. \(\begin{bmatrix} 0 & -1 \\ 2 & 0 \end{bmatrix}\). \(\mathbf{e}_1\) goes to the positive y-axis and \(\mathbf{e}_2\) to the negative x-axis: a \(90^\circ\) anticlockwise rotation combined with stretching the original x-direction by 2 (precisely: scale x by 2, then rotate \(90^\circ\); check: \(R_{90}\begin{bmatrix}2&0\\0&1\end{bmatrix} = \begin{bmatrix}0&-1\\2&0\end{bmatrix}\)). \(\det = 0\cdot 0 - (-1)(2) = 2\): areas double, orientation kept.

  2. Rows: \((1\cdot 3 + 2\cdot 4,\ 0\cdot 3 + (-1)\cdot 4) = (11, -4)\). Columns: \(3(1, 0) + 4(2, -1) = (3 + 8, 0 - 4) = (11, -4)\).

  3. \(AB = \begin{bmatrix} 2 & 1 \\ 4 & 3 \end{bmatrix}\) (the columns of \(A\) swapped), \(BA = \begin{bmatrix} 3 & 4 \\ 1 & 2 \end{bmatrix}\) (the rows of \(A\) swapped). \(B\) swaps coordinates. In \(AB\), \(B\) acts first on the input, swapping which basis vector goes where; in \(BA\), it acts last, swapping the output’s coordinates. Different, so \(AB \neq BA\).

  4. \(\det A = 4 - 3 = 1\), \(A^{-1} = \begin{bmatrix} 2 & -3 \\ -1 & 2 \end{bmatrix}\). \(\mathbf{x} = A^{-1}(7, 4) = (14 - 12,\ -7 + 8) = (2, 1)\). Check: \(4 + 3 = 7\), \(2 + 2 = 4\). ✓

  5. Determinant 0 means areas become 0: the plane is squashed onto a line (or a point). Then many different inputs land on the same output (whole lines of them collapse onto single points), so given an output you can’t tell which input it came from. An inverse would have to send one point to many, which no function can do.

  6. \(\mathbf{e}_1 = (1, 0)\) rotates to \((\cos\theta, \sin\theta)\) by definition of cos and sin on the unit circle; \(\mathbf{e}_2\) at \(90^\circ\) rotates to angle \(90^\circ + \theta\), i.e. \((-\sin\theta, \cos\theta)\). These are the columns: \(\begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix}\). At \(45^\circ\), \(c = s = \tfrac{\sqrt{2}}{2}\): \((c - s,\ s + c) = (0, \sqrt{2})\). Length \(\sqrt{2}\) preserved; the vector now points straight up. ✓

  7. \(\begin{bmatrix} 1 & 0 & 5 \\ 0 & 1 & -2 \\ 0 & 0 & 1 \end{bmatrix}\). Any \(2\times 2\) matrix sends \(\mathbf{0}\) to \(\mathbf{0}\), but a translation moves the origin to \((5, -2)\), so translation is not linear and no \(2\times 2\) matrix represents it.

  8. \(W\) is \(128\times 512\), \(\mathbf{b}\) has 128 entries. \(W\mathbf{x}\) needs \(128 \times 512 = 65\,536\) multiplications.