Chapter 9: Linear Algebra
Linear algebra is the study of linear maps between vector spaces. Every matrix represents a linear transformation, and every linear transformation can be represented by a matrix once you choose bases. That duality, between abstract maps and concrete arrays of numbers, is the central organizing idea of the subject. Eigenvalues reveal the intrinsic scaling behaviour of a transformation, and inner products let you measure angles and distances, which is what makes projection and approximation possible.
Concepts from other sections (18)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Eigenvector / eigenvalue: a non-zero and scalar with . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Inner product: . Read more: 9.6 Inner products, projections, cosine similarity, and top-k
- Spectral radius: . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Singular value decomposition: with orthonormal , and non-negative descending . Read more: 9.5 SVD, Eckart-Young low rank, and least squares
- Cosine similarity: the inner product divided by both lengths; depends only on direction. Read more: 9.6 Inner products, projections, cosine similarity, and top-k
- Partial pivoting: swapping the row with the largest absolute entry (among rows and below) into the pivot position before eliminating. Read more: 9.2 Gaussian elimination and LU with partial pivoting
- Complex number: a point of the plane with the multiplication defined by . Read more: 6.2 Trigonometry, rotations, complex numbers, and Euler’s formula
- Sign rule: flipping signs so that , which makes the factorization unique. Read more: 9.3 Orthogonality, Householder QR, and orthogonal initialization
- Power iteration: repeated multiplication and normalization, converging to the dominant eigenvector. Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Inverse iteration: power iteration on , finding the eigenvalue nearest the shift . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- QR algorithm: the iteration , converging to block upper triangular (real Schur) form. Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Balanced split: , , so both factors carry the same scale. Read more: 9.5 SVD, Eckart-Young low rank, and least squares
- PiSSA: initializing the adapter at the top- singular part of and freezing the residual. Read more: 12.6 LoRA: low-rank adaptation with PiSSA initialization and merging in AI Engineering
- Normal equations: , the least-squares optimality condition, which squares the condition number if solved directly. Read more: 9.5 SVD, Eckart-Young low rank, and least squares
- roofline: the bound on a loop’s speed from peak compute , memory bandwidth , and arithmetic intensity . Read more: 22.3 Cache-blocked, packed, batch-invariant matmul in C in AI Engineering
- Injective: no two inputs share an output; for a dict, no value appears twice. Read more: 11.2 Injective, surjective, bijective: the GPT-2 byte map
- Orthonormal: a set of unit-length vectors that are pairwise orthogonal. Read more: 9.3 Orthogonality, Householder QR, and orthogonal initialization
- Covariance: , a measure of linear co-movement; zero does not imply independence. Read more: 13.10 Probability problem set, part b: joint distributions, covariance, MLE
For anyone building machine learning systems, this is the mathematics that everything else runs on. A neural network layer is a matrix product. An embedding is a vector, and similarity between embeddings is an angle. Whether a recurrent network’s gradients explode is a question about eigenvalues; how to compress a weight matrix or start a low-rank adapter is a question about singular values; how to fit a scaling law to a handful of training runs is a least-squares problem. This chapter builds each of those tools from first principles, in code you write yourself, and explains why the numerically careful version is the right one.
The arc of the chapter follows the tools in the order they build on each other. It starts with the matrix product and how matrices are laid out in memory. It then learns to undo a product by Gaussian elimination and LU, and to build orthogonal matrices by Householder QR. QR becomes the engine for eigenvalues and the spectral radius, which in turn leads to the singular value decomposition, low-rank approximation, and least squares. The last section returns to the geometry of inner products, cosine similarity, and nearest-neighbour search. Two problem sets let you work the same ideas by hand.
Learning objectives
- Solve linear systems systematically by elimination, read off an LU factorization with partial pivoting, and understand the geometry of solution sets.
- Work with vector spaces abstractly: subspaces, bases, and dimension, and the rank-nullity theorem that ties a map’s kernel to its image.
- Represent linear maps as matrices, compose them by multiplication, and explain the connection between transformations and matrix products.
- Compute eigenvalues and eigenvectors, use them to predict the behaviour of repeated multiplication, and compute the spectral radius of matrices with complex eigenvalues.
- Apply inner products, orthogonality, projections, the SVD, and least squares, the backbone of low-rank methods and of modern machine learning.
Before you begin
Section titled “Before you begin”The chapter assumes no previous linear algebra. You should be comfortable with high-school algebra and with Python and NumPy arrays, shapes, and views, covered in Python and NumPy in Programming and Algorithms. Complex numbers and 2D rotations from Trigonometry, rotations, complex numbers, and Euler’s formula help with the eigenvalue section, and the orthogonal initializer draws normal random numbers from Random variables, expectation, variance, and normal draws by Box-Muller. Throughout, it pays to verify computations by hand first and then check them with NumPy, and to focus on why a theorem holds rather than memorizing the procedure.
In this chapter
Section titled “In this chapter”- Vectors, matrices, row-major layout, and matmul. The matrix product from its definition, how strides and transposes decide which stored element is read, and why
beta == 0must never read the old output. The result is the reference that faster kernels are checked against. - Gaussian elimination and LU with partial pivoting. Undoing a matrix product: elimination as a factorization , why pivoting is required for correct answers, and why you factor once and solve many times.
- Orthogonality, Householder QR, and orthogonal initialization. Matrices that preserve lengths, the Householder construction that stays orthogonal to machine precision, the sign rule that makes QR unique, and an orthogonal initializer for recurrent weights.
- Eigenvalues, power iteration, and the spectral radius. Power iteration, inverse iteration with one LU factorization, and the QR algorithm for rotations, where power iteration never converges. The spectral radius decides whether gradients explode or vanish.
- SVD, Eckart-Young low rank, and least squares. The singular value decomposition by one-sided Jacobi, the best low-rank approximation and the balanced split used by PiSSA, and least squares by QR instead of the normal equations.
- Inner products, projections, cosine similarity, and top-k. Angles between vectors, safe handling of zero vectors, projection onto a line, and exact top- search that is reproducible across runs and languages.
- Linear algebra problem set, part a. Forty-eight problems with worked answers on elimination, LU, bases, rank, determinants, eigenvalues, and QR. Best after sections 2 to 4.
- Linear algebra problem set, part b. Problems with worked answers on inner products, SVD and low rank, and the FLOP and byte accounting behind the roofline model. Best after sections 5 and 6.
The subject at a glance
Section titled “The subject at a glance”The sections above build specific tools. This overview collects the classical ideas they rest on, each with a short worked example, so you have the whole subject in view. The textbook sections named in each part refer to Hefferon’s free Linear Algebra, listed under further reading, which covers each topic in full with exercises.
Linear systems and Gauss’s method
Section titled “Linear systems and Gauss’s method”A linear system is a set of linear equations , and so on. A matrix is in echelon form when each leading entry is to the right of the leading entry in the row above; in reduced echelon form each leading entry is also 1 and the only nonzero entry in its column. A free variable corresponds to a non-pivot column and parameterizes the solution set.
Three results organize the topic. Gauss’s method says every matrix can be brought to echelon form by row operations (swap, scale, replacement): you eliminate variables one at a time, as you would by hand, but in a disciplined order. The reduced echelon form is unique: the path of row operations may differ, but the destination captures intrinsic information about the system. And the general solution of is one particular solution plus the general solution of : the homogeneous solution set, shifted to pass through a particular solution.
For example, solve , , . The augmented matrix is . gives ; gives ; gives . The last row says , so the system is inconsistent: it has no solution. (Hefferon ch. 1, sections I.1 to I.3; essential exercises I.1 #1.1 to 1.8, I.2 #2.10 to 2.16, I.3 #3.18 to 3.22; challenge I.3 #3.25 to 3.28.)
Vector spaces
Section titled “Vector spaces”A vector space is a set with addition and scalar multiplication satisfying ten axioms: closure, associativity, commutativity, identity, and inverses for addition; closure, associativity, distributivity, and identity for scalar multiplication. A subspace is a nonempty subset closed under both operations. A linear combination is , and the span of a set is all its linear combinations. Vectors are linearly independent if implies every . A basis is an independent spanning set, and the dimension is the number of vectors in any basis.
That definition of dimension is well defined because of the basis theorem: any two bases of a finite-dimensional space have the same number of elements, so dimension is intrinsic to the space, not an artifact of a basis choice. If is a subspace of , then , with equality exactly when . And any independent set can be extended to a basis, while any spanning set can be reduced to one.
For example, is a basis of . Independence: gives , , . The first two give ; the third then gives , so . Three independent vectors in form a basis. (Hefferon ch. 2, sections I to III; essential I #1.18 to 1.24, II #1.1 to 1.12, III #2.10 to 2.18; challenge III #3.14 to 3.18.)
Maps between spaces
Section titled “Maps between spaces”A linear map satisfies . Its kernel is and its range is . Its matrix representation has as columns the coordinate vectors of with respect to the basis .
The rank-nullity theorem, , says the input space splits into the part that collapses to zero and the part that survives, with every dimension accounted for. Every linear map between finite-dimensional spaces is represented by a matrix, given bases, and conversely: matrices are linear maps written in coordinates. And if is the change-of-basis matrix from to , the matrix of in is : the same transformation looks different in different coordinates, and the representations are related by conjugation.
For example, sends and , so its matrix is . Its kernel solves and , so : the kernel is trivial and is injective. By rank-nullity the rank is 2, so is also surjective. (Hefferon ch. 3, sections I to IV; essential I #1.14 to 1.20, II #2.10 to 2.18, IV #1.5 to 1.12; challenge IV #4.1 to 4.6.)
Determinants
Section titled “Determinants”The determinant of a square matrix is the unique scalar function that is multilinear and alternating in the rows, with for the identity matrix , the matrix with ones on the diagonal and zeros elsewhere, which leaves every vector unchanged. Cofactor expansion along row computes it as , where the minor is the determinant of the matrix with row and column deleted.
is invertible exactly when : the determinant is the signed volume scaling factor of the transformation, and zero volume means collapse, with information lost. , because composing transformations multiplies their volume factors. : the row and column pictures carry the same volume information. And Cramer’s rule, with column replaced by , isolates each variable by a ratio of determinants, elegant but computationally expensive for large systems.
For example, expand along the first column: . Since the determinant is nonzero, the matrix is invertible. (Hefferon ch. 4, sections I to III; essential I #1.1 to 1.8, II #1.1 to 1.6, III #1.1 to 1.8; challenge III #2.1 to 2.4.)
Eigenvalues and eigenvectors
Section titled “Eigenvalues and eigenvectors”An eigenvalue is a scalar with for some nonzero eigenvector . The eigenvalues are the roots of the characteristic polynomial , and the eigenspace is the set of eigenvectors for together with zero. is diagonalizable if with invertible and diagonal.
An matrix is diagonalizable exactly when it has independent eigenvectors: with a basis of eigenvectors, the matrix acts as pure scaling along those directions. If it has distinct eigenvalues, it is diagonalizable, because eigenvectors for different eigenvalues are automatically independent. The Cayley-Hamilton theorem says every square matrix satisfies its own characteristic polynomial, . And the spectral theorem says a real symmetric matrix has real eigenvalues and orthogonal eigenvectors: symmetric matrices stretch along perpendicular directions. Diagonalization makes powers cheap, .
For example, diagonalize . . For , gives ; for , gives . So with and . (Hefferon ch. 5, sections I and II; essential I #1.1 to 1.10, II #1.1 to 1.8 and #2.1 to 2.6; challenge II #3.1 to 3.6.)
Inner product spaces
Section titled “Inner product spaces”The inner product in is ; more generally it is a positive-definite symmetric bilinear form. The norm is , and and are orthogonal when . An orthonormal basis has for and . The orthogonal projection onto a subspace with orthonormal basis is , and the least-squares solution minimizes .
The Cauchy-Schwarz inequality , with equality exactly when and are parallel, says the projection of one vector onto another cannot exceed its length. Gram-Schmidt turns a basis into an orthonormal one: at each step, strip away the components along the directions already found and normalize what is genuinely new. The projection is the closest point in to , because the error is orthogonal to . And the least-squares solution satisfies the normal equations : project onto the column space, and the residual is orthogonal to every column. (Section 5 explains why, in floating point, you solve them through QR instead.)
For example, apply Gram-Schmidt to . First, . Next, , and . The third step projects onto and , subtracts, and normalizes. (Hefferon ch. 3, section VI, exercises #1.1 to 1.10, and Strang ch. 4; MIT 18.06 problem set 4, #4.1 to 4.4, challenge #4.5 to 4.8, and least-squares fitting exercises.)
Techniques at a glance
Section titled “Techniques at a glance”The classical techniques, side by side:
| Technique | When to use | Key formula or idea |
|---|---|---|
| Gaussian elimination | solve linear systems | row reduce to echelon form |
| Back substitution | read off solutions from echelon form | work bottom to top |
| Rank-nullity | relate kernel and image dimensions | |
| Cofactor expansion | compute determinants | expand along the row or column with the most zeros |
| Characteristic polynomial | find eigenvalues | solve |
| Diagonalization | simplify matrix powers | |
| Gram-Schmidt | orthonormalize a basis | subtract projections, normalize |
| Least squares | solve overdetermined systems | , solved stably by QR |
Key terms
Section titled “Key terms”- Linear map: a function between vector spaces with ; once bases are chosen, every linear map is a matrix.
- Linear independence: vectors are linearly independent when the only combination equal to zero has every , so none is redundant.
- Basis: a linearly independent set that spans the space; every vector is exactly one combination of basis vectors, and the number of them is the dimension.
- Null space / kernel: the vectors a matrix sends to zero, ; a nonzero null space means the map loses information.
- Rank-nullity theorem: ; every input dimension either collapses to zero or survives.
- Identity matrix: the square matrix with ones on the diagonal and zeros elsewhere; for every , so it is the “do nothing” transformation and .
- Inverse matrix / invertible matrix: undoes , with ; it exists exactly when , and in practice you solve with a factorization instead of forming it.
- Determinant: a single number for a square matrix: the factor by which scales signed volume. It is zero exactly when squashes space flat and so cannot be inverted, and .
- Characteristic polynomial: , whose roots are the eigenvalues of .
- Change of basis: rewriting a matrix in new coordinates as ; the transformation is the same, only its description changes.
- Cramer’s rule: , solving by ratios of determinants; useful by hand, far too slow for large systems.
Where linear algebra shows up
Section titled “Where linear algebra shows up”These ideas reach well beyond this book. Matrix multiplication drives computer graphics (rotation, scaling, projection) and every layer of a neural network, and attention is a sequence of matrix operations. Google’s PageRank is the dominant eigenvector of a stochastic link matrix. The SVD and PCA underlie dimensionality reduction and recommendation systems, where matrix factorization predicts ratings. Least squares is linear regression and curve fitting, developed further in the Probability and Statistics chapter. Linear independence is the issue behind multicollinearity in feature selection. Change of basis is coordinate transforms and the Fourier and wavelet bases of Signals and Images. Sparse matrices represent graphs as adjacency matrices. In quantitative finance, covariance matrices and PCA drive portfolio optimization and risk models; in robotics, kinematics is a chain of rotation matrices and coordinate transforms.
Further reading
Section titled “Further reading”- Jim Hefferon, Linear Algebra (free, GFDL): the textbook the overview above follows, with exercises for every topic.
- 3Blue1Brown, Essence of Linear Algebra: short videos that build geometric intuition; worth watching before or alongside each section.
- Gilbert Strang, MIT OCW 18.06, with Introduction to Linear Algebra: an excellent second perspective on tricky topics.
- Lloyd Trefethen and David Bau, Numerical Linear Algebra: the numerical side, from QR and pivoting to eigenvalue algorithms.