Two puzzles with one theory behind them
Balancing a reaction. In photosynthesis, a leaf turns carbon dioxide and water into glucose and oxygen:
Counting atoms of carbon, hydrogen and oxygen on both sides gives three equations in four unknowns:
Must there be a solution other than ? Is it unique up to scaling? (Chemists find .) The answers — yes, and yes — come from a single theorem about dimensions, the rank–nullity theorem, which says that three equations can "use up" at most three of the four degrees of freedom.
Growth. The Fibonacci numbers satisfy . In matrix form,
so computing means computing powers of a matrix. The ratios approach the golden ratio . Why that number? Because is an eigenvalue of the matrix: there is a direction that the matrix only stretches, by the factor , and after many steps that direction wins.
The same two questions — solve a linear system, understand repeated application of a linear map — appear in circuit analysis, economics, computer graphics, statistics, quantum mechanics, search engines and machine learning. Linear algebra is the theory that answers both. It starts where school algebra stops: from simultaneous linear equations in two or three unknowns, with scalars from the real numbers (or any other field).
Linear maps as transformations of space
A matrix moves every point of the plane to . Because and , the whole picture is determined by where the two basis vectors and go: they go to the columns of . The square grid becomes a grid of parallelograms, the origin stays put, and straight lines stay straight (or collapse).
Three numbers measure what happens:
- the determinant is the factor by which areas are multiplied, with a minus sign if the map flips the plane over;
- the rank is the dimension of the image: if the plane goes onto the plane, if it is squashed onto a line, if everything goes to the origin;
- the eigenvectors are the directions that are not turned at all, only stretched (by the eigenvalue).
A linear map of the plane
Drag the entries or pick a preset. Watch the columns, the area of the unit square, the flag and the dashed invariant lines.
- image of the grid
- image of the unit square
- image of the flag
- before the transformation
- invariant line
The columns of A are the images of e₁ = (1, 0) and e₂ = (0, 1): Ae₁ = (1, 0.5), Ae₂ = (1, 1.5)
det A = ad − bc = 1
The unit square (area 1) becomes a parallelogram of area |det A| = 1. Since det A > 0, orientation is preserved.
Invariant lines (real eigenvectors)
- λ₁ = 2, v₁ = (1, 1)
- λ₂ = 0.5, v₂ = (1, −0.5)
Vectors on the two dashed lines are only stretched, by the factors λ₁ = 2 and λ₂ = 0.5; every other direction is turned.
Try the "singular" preset: the whole plane collapses onto a line, the determinant is , and some non-zero vectors are sent to . That collapse is exactly what makes a system of equations fail to have a unique solution. Try "rotation": no real direction survives unturned, so there are no real eigenvectors.
Definitions
Throughout, is a field: , , , or the two-element field with (see algebraic structures). Elements of are called scalars.
Definition— vector space
A vector space over is a set with an addition and a scalar multiplication such that is an abelian group (with zero vector ) and, for all and ,
A subspace is a subset containing and closed under addition and scalar multiplication; it is a vector space in its own right.
Definition— span, linear independence, basis, dimension
A linear combination of is a vector with . Their span is the set of all linear combinations, the smallest subspace containing them. The list is linearly independent if
and dependent otherwise. A basis of is a linearly independent list that spans ; then every is for unique scalars , its coordinates. is finite-dimensional if some finite list spans it, and then is the number of vectors in a basis — a definition that only makes sense once we prove that all bases have the same size (the exchange lemma, below).
Definition— linear map, kernel, image, rank
A map between vector spaces over is linear if
Then . Its kernel and image are subspaces of and . The rank of is and its nullity is . A linear map is injective if and only if , because .
Definition— matrix of a linear map
Let be a basis of and a basis of . The matrix of with respect to and is the matrix whose -th column holds the coordinates of :
For and with their standard bases, is the matrix with . The product of an matrix and an matrix is the matrix with entries .
Definition— determinant
The determinant of an matrix is
the sum over all permutations of , where according as is a product of an even or odd number of swaps. For : .
Definition— eigenvalue, eigenvector, diagonalisable
Let be linear. A scalar is an eigenvalue of if for some non-zero vector , called an eigenvector. The eigenspace consists of the eigenvectors for together with ; its dimension is the geometric multiplicity of . For a square matrix , the characteristic polynomial is , and the multiplicity of as a root of is its algebraic multiplicity. is diagonalisable (over ) if is diagonal for some invertible matrix with entries in .
Examples and non-examples
Example— Vector spaces you already know (and some you may not)
- , lists of scalars; , with the standard basis .
- The polynomials of degree at most , with basis : dimension .
- The solutions of the differential equation on : a vector space of dimension , with basis .
- : the seven-bit words used in error-correcting codes. Over we have for every .
- All functions : a vector space that is not finite-dimensional (the functions are independent).
Not subspaces of : the plane (it does not contain ); the octant (not closed under multiplication by ); the union of the - and -axes in (closed under scaling, but is on neither axis).
Example— Gaussian elimination, worked
Solve and . Row-reduce the augmented matrix: subtract twice row 1 from row 2, then subtract the new row 2 from row 1:
This is the reduced row echelon form: each non-zero row starts with a pivot , which is the only non-zero entry in its column. The pivot columns belong to and ; the column of has no pivot, so is free. Reading off, and :
The solution set is a line: one particular solution plus every multiple of , which spans the null space of the coefficient matrix. A system is inconsistent exactly when elimination produces a row with , that is, the equation .
Example— Differentiation as a matrix
Let be the polynomials of degree at most with basis , and . Since , , and , the columns of are these coordinates:
is the constants (dimension ) and is the polynomials of degree at most (dimension ); indeed . Since , any eigenvalue satisfies , so , and has dimension : has too few eigenvectors to be diagonalisable.
Example— Maps that are not linear
on is not linear: it moves . (It is affine: linear followed by a translation; see transformation geometry.) is not linear: . A linear map need not be injective: the projection sends the whole -axis — a line through the origin — to the single point .
Linear systems
A system of linear equations in unknowns is with an matrix. The elementary row operations are: swap two rows; multiply a row by a non-zero scalar; add a multiple of one row to another.
Theorem— Proposition (row operations do not change the solutions)
If an augmented matrix is turned into by elementary row operations, then and have exactly the same solutions.
Proof
Each new equation is a linear combination of the old ones, so every solution of the old system solves the new one. Each operation can be undone by an operation of the same kind (swap back; multiply by ; subtract the multiple again), so by the same argument every solution of the new system solves the old one.
∎
By repeatedly choosing a pivot, scaling it to and clearing its column, any matrix can be brought to reduced row echelon form; this is Gaussian elimination. Its output is read off as in the worked example: the system is consistent if and only if no pivot lies in the last column, and then the free variables can be chosen arbitrarily and determine the pivot variables uniquely.
Theorem— Theorem (structure of the solution set)
Let be linear and . If is one solution of , then the set of all solutions is the translate
In particular, a consistent system has a unique solution exactly when .
Proof
By linearity , so holds if and only if , that is, , that is, .
∎
So the solution set of a linear system is empty, or a point, or a line, plane, … that need not pass through the origin, parallel to the null space. This is the shape of the solutions of linear differential equations too: general solution = particular solution + general solution of the homogeneous equation.
Bases and dimension
Theorem— Lemma (adding a vector outside the span)
If are linearly independent and , then are linearly independent.
Proof
Suppose . If then lies in the span, which is false; so , and then independence of the gives .
∎
Theorem— Theorem (Steinitz exchange lemma)
If are linearly independent in and span , then .
Proof
We replace the 's by 's one at a time, keeping a spanning list. We claim that for each , after renumbering the 's, and the list spans . For this is the hypothesis.
Suppose it holds for some . Since the list spans, for some scalars. If every were — in particular, if no 's were left, — then would be a combination of , contradicting independence. So , and after renumbering . Solving for ,
so this new list still spans everything the old one did, namely . This proves the claim for , and with it gives .
∎
Theorem— Corollary (invariance of dimension)
Any two bases of a finite-dimensional vector space have the same number of elements.
Proof
If and are bases, each is independent and each spans, so the exchange lemma gives and .
∎
Theorem— Corollary (extending to a basis)
In a vector space of dimension , every linearly independent list has at most vectors and can be extended to a basis; every subspace is finite-dimensional with .
Proof
An independent list has at most elements by the exchange lemma (a basis spans). If an independent list does not span, add a vector outside its span; by the lemma it stays independent. This must stop after at most additions, and it stops only at a spanning list, i.e. a basis. For a subspace , start from the empty list and add vectors of outside the current span: the lists stay independent in , so the process stops after at most steps, at a basis of .
∎
The rank–nullity theorem
Theorem— Theorem (rank–nullity)
Let be linear with finite-dimensional. Then is finite-dimensional and
Proof
Choose a basis of and extend it to a basis of , so . We show that is a basis of .
Spanning. Any is , and , so .
Independence. If then , so and for some . Then is a relation among the vectors of a basis of , so all (and ) are .
Hence and .
∎
For a matrix , Gaussian elimination makes this concrete: is the number of pivots (the pivot columns of form a basis of its column space, because row operations preserve the linear relations between columns), and the nullity is the number of free variables (each free variable gives one basis vector of the null space, as in the worked example). Every column is either a pivot column or a free one.
Theorem— Corollary (more unknowns than equations)
A homogeneous system of equations in unknowns has a non-zero solution.
Proof
The image of lies in , so has dimension at most . By rank–nullity , so contains a non-zero vector.
∎
For photosynthesis, , so a non-zero balancing exists. Elimination shows the rank is exactly , so the null space is a line: the balancing is unique up to scaling.
Theorem— Corollary (injective, surjective, bijective)
If is linear and is finite-dimensional, then is injective is surjective is bijective.
Proof
is injective iff , iff (by rank–nullity) , iff (a subspace of full dimension is the whole space: a basis of it is an independent list of vectors, which cannot be extended, so it already spans ).
∎
This fails in infinite dimensions: on sequences, the shift is injective but not surjective.
Matrices, composition and change of basis
Theorem— Theorem (composition is matrix multiplication)
Let and be linear, and fix bases , , . Then is linear, and .
Proof
Linearity: , and similarly for scalars. For the matrix, with and ,
so the entry of is .
∎
This is why matrices are multiplied rows-into-columns. It also proves for free that matrix multiplication is associative, because composition of functions is. It is not commutative, because composition is not: with and , but . Rotations of the plane do commute: multiplying the rotation matrices produces the addition formulas for sine and cosine and gives .
Theorem— Proposition (change of basis)
Let and be bases of , and let be the matrix whose -th column holds the -coordinates of the -th vector of . Then is invertible, for every , and for every linear ,
Proof
is the matrix of the identity map of from -coordinates to -coordinates, so ; the matrix the other way is an inverse. Then for all , and a matrix is determined by what it does to all coordinate vectors.
∎
Matrices and are called similar: they describe the same linear map in two coordinate systems. Everything intrinsic to the map — rank, determinant, trace, eigenvalues, characteristic polynomial — is the same for similar matrices.
Determinants and invertibility
We use the following properties of the determinant, all derived from the permutation formula (see Axler, ch. 9, or Strang, ch. 5):
- is linear in each column when the other columns are fixed;
- it is alternating: if two columns are equal, (so swapping two columns changes the sign);
- ;
- it is multiplicative: .
Properties 1 and 2 almost characterise the determinant. Let be any function of matrices that is linear in each column and alternating. Expanding each column of by multilinearity writes as a sum, over all functions from to itself, of . Alternation kills every term with not injective, and for a permutation the swaps that sort into give . Comparing with the permutation formula: . Property 4 follows: for fixed , the function is linear in each column of (the -th column of is ) and alternating (equal columns of give equal columns of ), so . Geometrically, is the factor by which multiplies areas () or volumes (), and the sign records orientation.
Theorem— Theorem (invertibility)
For an matrix over a field, the following are equivalent:
- is invertible;
- only for ;
- the columns of are linearly independent;
- ;
- .
Proof
(2 ⇔ 3) where are the columns, so a non-zero solution of is exactly a dependence relation among the columns.
(2 ⇔ 4 ⇔ 1) By rank–nullity, iff ; and by the corollary on injective maps, this holds iff is bijective. The inverse of a linear bijection is linear (apply the bijection to ), and its matrix is an inverse of . Conversely an invertible is injective.
(1 ⇒ 5) , so .
(5 ⇒ 3) Contrapositive. If the columns are dependent, some column is a combination of the others: . By linearity in column , , where is with column replaced by . Each has two equal columns, so and .
∎
For matrices, , which visibly needs .
Eigenvalues and diagonalisation
Theorem— Proposition (eigenvalues are roots of the characteristic polynomial)
is an eigenvalue of the square matrix if and only if . Hence an matrix has at most eigenvalues.
Proof
for some iff has a non-zero solution, iff (invertibility theorem) . By the permutation formula, is a monic polynomial of degree in , so it has at most roots.
∎
The rotation has : no real eigenvalues, but eigenvalues over . Over every square matrix has an eigenvalue, by the fundamental theorem of algebra; this is one reason complex scalars are so useful.
Theorem— Theorem (eigenvectors for distinct eigenvalues are independent)
If are eigenvectors of with pairwise distinct eigenvalues , then are linearly independent.
Proof
Induction on . For , is independent. Let , assume the result for , and suppose . Applying gives . Subtracting times the first relation,
By the induction hypothesis every , and , so . Then with , so .
∎
Theorem— Theorem (diagonalisability)
An matrix over is diagonalisable if and only if has a basis of eigenvectors of ; then where the columns of are the eigenvectors and the diagonal of lists their eigenvalues. In particular, if has distinct eigenvalues in , it is diagonalisable.
Proof
Write for the columns of and . The -th column of is and that of is , so says exactly that for each . is invertible iff its columns form a basis (invertibility theorem), so " with invertible" says exactly "the are a basis of eigenvectors". With distinct eigenvalues, choose one eigenvector for each; they are independent by the previous theorem, and independent vectors in form a basis.
∎
More generally — by the same independence argument applied to eigenspaces — is diagonalisable if and only if the geometric multiplicities of its eigenvalues add up to .
Theorem— Proposition (a matrix that cannot be diagonalised)
is not diagonalisable over any field.
Proof
, so is the only eigenvalue, and is one-dimensional: there is no basis of eigenvectors. Here is a second proof, the one formalised in Lean, that avoids eigenvectors. Suppose with invertible and diagonal. Since ,
so (multiply by ), so each diagonal entry satisfies , i.e. . Then , so — false.
∎
Example— Fibonacci numbers by diagonalisation
has , with distinct roots and , so it is diagonalisable over . Since for both roots, . Write (using ). Then
Since , and : the eigenvector with the larger eigenvalue dominates. This is Binet's formula.
Linear algebra in Lean and Mathlib
Mathlib's linear algebra is written for modules over rings, and specialises to vector spaces over a field K: Module K V is the vector-space structure, V →ₗ[K] W the type of linear maps, LinearMap.ker and LinearMap.range the kernel and image, Module.finrank K V the dimension (as a natural number), and Matrix m n K the matrices, acting on vectors by A *ᵥ x. The lesson's module proves several results again from basic facts (independent) and cites the library for others.
Linear systems. The structure theorem is a two-line rewrite, exactly the human proof ; the worked elimination is then checked in full: the solutions of , are precisely , both directions of the "if and only if".
/-- **Solution sets are translates of the kernel.** If `x₀` is one solution of `f x = b`,
then `x` is a solution exactly when `x - x₀` lies in the kernel of `f`: the general solution is
"one particular solution plus the general solution of the homogeneous system". The proof is
the human one: `f x - f x₀ = f (x - x₀)` by linearity. -/
theorem solutions_translate_ker {K V W : Type*} [Field K] [AddCommGroup V] [Module K V]
[AddCommGroup W] [Module K W] (f : V →ₗ[K] W) {x₀ : V} {b : W} (h₀ : f x₀ = b) (x : V) :
f x = b ↔ x - x₀ ∈ LinearMap.ker f := by
rw [LinearMap.mem_ker, map_sub, h₀, sub_eq_zero]/-- The coefficient matrix of the worked example in the lesson:
`x + 2y + z = 4`, `2x + 4y + 3z = 9` (two equations, three unknowns). -/
def systemMatrix : Matrix (Fin 2) (Fin 3) ℚ := !![1, 2, 1; 2, 4, 3]/-- **The worked Gaussian elimination, checked.** Elimination reduces the system to
`x + 2y = 3`, `z = 1` with `y` free, so the solutions are exactly
`(3, 0, 1) + t·(-2, 1, 0)`: a line, the translate of the one-dimensional null space by a
particular solution. Here `t` is the free variable `y`. -/
theorem worked_system (x : Fin 3 → ℚ) :
systemMatrix *ᵥ x = ![4, 9] ↔ ∃ t : ℚ, x = ![3, 0, 1] + t • ![-2, 1, 0] := by
constructor
· intro h
have h0 := congrFun h 0
have h1 := congrFun h 1
simp [systemMatrix, mulVec, dotProduct, Fin.sum_univ_three] at h0 h1
refine ⟨x 1, ?_⟩
funext i
fin_cases i <;> simp <;> linarith
· rintro ⟨t, rfl⟩
funext i
fin_cases i <;> simp [systemMatrix, mulVec, dotProduct, Fin.sum_univ_three] <;> ringComposition and matrices. Mathlib's Matrix.toLin' turns a matrix into the linear map ; that it turns products into composites is the theorem of this lesson. Then two independent facts: the explicit non-commuting pair, and the rotation matrices composing by adding angles.
/-- **Composition is matrix multiplication.** The linear map of `M * N` is the composite
"first `N`, then `M`". This is Mathlib's `Matrix.toLin'_mul`; it is the reason matrix
multiplication is defined the way it is. -/
theorem toLin_mul {K : Type*} [Field K] {l m n : Type*} [Fintype m] [DecidableEq m]
[Fintype n] [DecidableEq n] (M : Matrix l m K) (N : Matrix m n K) :
Matrix.toLin' (M * N) = (Matrix.toLin' M).comp (Matrix.toLin' N) :=
Matrix.toLin'_mul M N/-- **Matrix multiplication is not commutative.** With `A = !![0, 1; 0, 0]` and
`B = !![0, 0; 1, 0]`, the top-left entries of `A * B` and `B * A` are `1` and `0`. -/
theorem mul_not_comm : ∃ A B : Matrix (Fin 2) (Fin 2) ℚ, A * B ≠ B * A := by
refine ⟨!![0, 1; 0, 0], !![0, 0; 1, 0], fun h => ?_⟩
have h00 := congrFun (congrFun h 0) 0
simp [Matrix.mul_apply, Fin.sum_univ_two] at h00/-- The matrix of the rotation of the plane by the angle `θ`: its columns are the images
`(cos θ, sin θ)` and `(-sin θ, cos θ)` of the standard basis vectors. -/
noncomputable def rot (θ : ℝ) : Matrix (Fin 2) (Fin 2) ℝ :=
!![Real.cos θ, -Real.sin θ; Real.sin θ, Real.cos θ]/-- **Rotations compose by adding angles.** Rotating by `β` and then by `α` is rotating by
`α + β`. Multiplying the matrices entry by entry turns this into the addition formulas for
cosine and sine (`Real.cos_add`, `Real.sin_add`). -/
theorem rot_mul_rot (α β : ℝ) : rot α * rot β = rot (α + β) := by
ext i j
fin_cases i <;> fin_cases j <;>
simp [rot, Matrix.mul_apply, Fin.sum_univ_two, Real.cos_add, Real.sin_add] <;> ringDimension and rank–nullity come from the library, whose proofs follow the same route as ours (Mathlib proves rank–nullity via the isomorphism , an equivalent formulation). The "more unknowns than equations" corollary is proved here from rank–nullity, mirroring the human proof line by line: bound the image by , subtract, and extract a non-zero vector from a subspace of positive dimension.
/-- **Invariance of dimension.** Any two finite bases of a vector space have the same number
of elements. Both are equal to `Module.finrank K V` by Mathlib's `Module.finrank_eq_card_basis`,
whose proof rests on the exchange argument given in the lesson. -/
theorem bases_same_card {K V : Type*} [Field K] [AddCommGroup V] [Module K V]
{ι ι' : Type*} [Fintype ι] [Fintype ι'] (b : Module.Basis ι K V) (b' : Module.Basis ι' K V) :
Fintype.card ι = Fintype.card ι' :=
(Module.finrank_eq_card_basis b).symm.trans (Module.finrank_eq_card_basis b')/-- **Rank–nullity.** For a linear map `f : V → W` with `V` finite-dimensional,
`dim (im f) + dim (ker f) = dim V`. This is Mathlib's `LinearMap.finrank_range_add_finrank_ker`. -/
theorem rank_nullity {K V W : Type*} [Field K] [AddCommGroup V] [Module K V]
[AddCommGroup W] [Module K W] [FiniteDimensional K V] (f : V →ₗ[K] W) :
Module.finrank K (LinearMap.range f) + Module.finrank K (LinearMap.ker f) =
Module.finrank K V :=
LinearMap.finrank_range_add_finrank_ker f/-- **More unknowns than equations.** A homogeneous system of `m` equations in `n > m`
unknowns has a non-zero solution. Proof from rank–nullity, as in the lesson:
`dim ker = n - dim im ≥ n - m > 0`, and a subspace of positive dimension contains a non-zero
vector. -/
theorem exists_nonzero_solution {K : Type*} [Field K] {m n : ℕ} (A : Matrix (Fin m) (Fin n) K)
(h : m < n) : ∃ x : Fin n → K, x ≠ 0 ∧ A *ᵥ x = 0 := by
have hrn := LinearMap.finrank_range_add_finrank_ker A.mulVecLin
have him : Module.finrank K (LinearMap.range A.mulVecLin) ≤ m := by
simpa using (LinearMap.range A.mulVecLin).finrank_le
have hdim : Module.finrank K (Fin n → K) = n := by simp
have hpos : 0 < Module.finrank K (LinearMap.ker A.mulVecLin) := by omega
obtain ⟨x, hx, hx0⟩ := Submodule.exists_mem_ne_zero_of_ne_bot
(Submodule.one_le_finrank_iff.mp hpos)
exact ⟨x, hx0, by simpa using hx⟩Invertibility. Two of the equivalences of the invertibility theorem, from Mathlib. (A.col is the family of columns of A; IsUnit A means has a two-sided inverse.)
/-- **The determinant test.** A square matrix over a field is invertible if and only if its
determinant is non-zero. This combines Mathlib's `Matrix.isUnit_iff_isUnit_det` with the fact
that the units of a field are its non-zero elements. -/
theorem isUnit_iff_det_ne_zero {K n : Type*} [Field K] [Fintype n] [DecidableEq n]
(A : Matrix n n K) : IsUnit A ↔ A.det ≠ 0 := by
rw [Matrix.isUnit_iff_isUnit_det, isUnit_iff_ne_zero]/-- **The column test.** A square matrix over a field is invertible if and only if its
columns are linearly independent: Mathlib's `Matrix.linearIndependent_col_iff_isUnit`. -/
theorem cols_independent_iff {K n : Type*} [Field K] [Fintype n] [DecidableEq n]
(A : Matrix n n K) : LinearIndependent K A.col ↔ IsUnit A :=
Matrix.linearIndependent_col_iff_isUnitEigenvectors. The two-eigenvector case of the independence theorem is proved exactly as on paper — apply , subtract times the relation, cancel — while the general statement is Mathlib's (proved there via the independence of the eigenspaces). Finally, the non-diagonalisability of , by the second proof above: , so , so .
/-- **Eigenvectors for distinct eigenvalues are independent** (two at a time). Suppose
`s • v + t • w = 0`. Applying `T` gives `s λ v + t μ w = 0`; subtracting `λ` times the first
equation leaves `t (μ - λ) w = 0`, so `t = 0` because `μ ≠ λ` and `w ≠ 0`; then `s v = 0`
forces `s = 0`. -/
theorem eigen_pair_independent {K V : Type*} [Field K] [AddCommGroup V] [Module K V]
(T : V →ₗ[K] V) {v w : V} {lam mu : K} (hv : T v = lam • v) (hw : T w = mu • w)
(hv0 : v ≠ 0) (hw0 : w ≠ 0) (hne : lam ≠ mu) : LinearIndependent K ![v, w] := by
rw [LinearIndependent.pair_iff]
intro s t hst
-- Apply `T` to the relation.
have hT : (s * lam) • v + (t * mu) • w = 0 := by
have := congrArg T hst
rw [map_add, map_smul, map_smul, hv, hw, map_zero, smul_smul, smul_smul] at this
exact this
-- Subtract `lam` times the relation.
have hdiff : (t * (mu - lam)) • w = 0 := by
have h2 : lam • (s • v + t • w) = 0 := by rw [hst, smul_zero]
calc (t * (mu - lam)) • w
= ((s * lam) • v + (t * mu) • w) - lam • (s • v + t • w) := by
rw [smul_add, smul_smul, smul_smul, mul_sub, sub_smul]; abel_nf; module
_ = 0 := by rw [hT, h2, sub_zero]
have ht : t = 0 := by
rcases smul_eq_zero.mp hdiff with h | h
· rcases mul_eq_zero.mp h with h' | h'
· exact h'
· exact absurd (sub_eq_zero.mp h').symm hne
· exact absurd h hw0
refine ⟨?_, ht⟩
rw [ht, zero_smul, add_zero] at hst
rcases smul_eq_zero.mp hst with h | h
· exact h
· exact absurd h hv0/-- **Eigenvectors for distinct eigenvalues are independent** (any number at a time). This is
Mathlib's `Module.End.eigenvectors_linearIndependent'`, proved there by showing that the
eigenspaces form an independent family of subspaces. -/
theorem eigenvectors_independent {K V ι : Type*} [Field K] [AddCommGroup V] [Module K V]
(T : Module.End K V) (μ : ι → K) (hμ : Function.Injective μ) (v : ι → V)
(hv : ∀ i, T.HasEigenvector (μ i) (v i)) : LinearIndependent K v :=
T.eigenvectors_linearIndependent' μ hμ v hv/-- **Not every matrix is diagonalisable.** The matrix `N = !![0, 1; 0, 0]` is not similar to
any diagonal matrix `D`: there is no invertible `P` with `N P = P D`. Proof from the lesson:
`N² = 0`, so `P D² = N² P = 0`, so `D² = 0` (cancel the invertible `P`), so every diagonal
entry of `D` is `0`; then `N P = P D = 0` and cancelling `P` again gives `N = 0`, which is
false. -/
theorem nilpotent_not_diagonalisable {K : Type*} [Field K] :
¬ ∃ (P : Matrix (Fin 2) (Fin 2) K) (d : Fin 2 → K),
IsUnit P ∧ !![0, 1; 0, 0] * P = P * Matrix.diagonal d := by
rintro ⟨P, d, hP, hNP⟩
set N : Matrix (Fin 2) (Fin 2) K := !![0, 1; 0, 0] with hN
have hNN : N * N = 0 := by
ext i j
fin_cases i <;> fin_cases j <;> simp [hN, Matrix.mul_apply, Fin.sum_univ_two]
-- `P D² = 0`.
have hPDD : P * (Matrix.diagonal d * Matrix.diagonal d) = 0 := by
calc P * (Matrix.diagonal d * Matrix.diagonal d)
= (P * Matrix.diagonal d) * Matrix.diagonal d := (Matrix.mul_assoc _ _ _).symm
_ = (N * P) * Matrix.diagonal d := by rw [hNP]
_ = N * (P * Matrix.diagonal d) := Matrix.mul_assoc _ _ _
_ = N * (N * P) := by rw [hNP]
_ = (N * N) * P := (Matrix.mul_assoc _ _ _).symm
_ = 0 := by rw [hNN, Matrix.zero_mul]
-- So `D² = 0`, hence `D = 0`.
have hDD : Matrix.diagonal d * Matrix.diagonal d = 0 := (hP.mul_right_eq_zero).mp hPDD
have hd : ∀ i, d i = 0 := by
intro i
have := congrFun (congrFun hDD i) i
simpa [Matrix.diagonal_mul_diagonal] using this
have hD : Matrix.diagonal d = 0 := by
ext i j
simp [Matrix.diagonal_apply, hd]
-- Then `N P = 0`, hence `N = 0`: a contradiction.
have hN0 : N = 0 := by
have : N * P = 0 := by rw [hNP, hD, Matrix.mul_zero]
exact (hP.mul_left_eq_zero).mp this
have h01 := congrFun (congrFun hN0 0) 1
simp [hN] at h01Not formalised here: the exchange lemma itself (it is inside Mathlib's proof that finrank is well defined), the permutation formula and multiplicativity of the determinant (Mathlib's Matrix.det and Matrix.det_mul), and Binet's formula (Mathlib has it as Real.coe_fib_eq).
Elimination by machine, and a census of matrices
Gaussian elimination is an algorithm, and computers run it billions of times a day. In floating-point arithmetic a tiny rounding error can turn a zero into and create a spurious pivot, so the rank of a matrix is numerically delicate. The first experiment works with exact fractions instead: it row-reduces the worked example, reads off the null space, and checks rank–nullity on 300 random integer matrices whose rank is controlled by building them as products of an and an matrix.
"""Gaussian elimination in exact arithmetic, and rank-nullity on many matrices.
The experiment row-reduces matrices with Python fractions, so every step is
exact: no rounding errors can create or destroy a pivot. It reduces the worked
example of the lesson, reads off a basis of the null space from the free
columns, and then checks rank + nullity = number of columns on a few hundred
random integer matrices whose rank is known in advance (they are built as a
product of an m x r and an r x n matrix). This is exact computation on finitely
many cases: evidence for the theorem, not a proof of it.
"""
import random
from fractions import Fraction
def rref(matrix):
"""Return (R, pivots): the reduced row echelon form and pivot columns."""
rows = [[Fraction(x) for x in row] for row in matrix]
m = len(rows)
n = len(rows[0]) if m else 0
pivots = []
r = 0
for c in range(n):
p = next((i for i in range(r, m) if rows[i][c] != 0), None)
if p is None:
continue
rows[r], rows[p] = rows[p], rows[r]
lead = rows[r][c]
rows[r] = [x / lead for x in rows[r]]
for i in range(m):
if i != r and rows[i][c] != 0:
factor = rows[i][c]
rows[i] = [a - factor * b for a, b in zip(rows[i], rows[r])]
pivots.append(c)
r += 1
if r == m:
break
return rows, pivots
def rank(matrix):
"""The number of pivots in the reduced row echelon form."""
return len(rref(matrix)[1])
def null_space(matrix):
"""A basis of {x : Ax = 0}, one vector per free column."""
reduced, pivots = rref(matrix)
n = len(matrix[0])
basis = []
for free in (c for c in range(n) if c not in pivots):
v = [Fraction(0)] * n
v[free] = Fraction(1)
for row, p in zip(reduced, pivots):
v[p] = -row[free]
basis.append(v)
return basis
def mat_vec(matrix, v):
"""The product A v."""
return [sum(Fraction(a) * x for a, x in zip(row, v)) for row in matrix]
def mat_mul(a, b):
"""The product of two matrices given as lists of rows."""
return [[sum(x * y for x, y in zip(row, col)) for col in zip(*b)]
for row in a]
def random_matrix_of_rank(rng, m, n, r):
"""An m x n integer matrix (B C with B m x r, C r x n); rank <= r."""
b = [[rng.randint(-4, 4) for _ in range(r)] for _ in range(m)]
c = [[rng.randint(-4, 4) for _ in range(n)] for _ in range(r)]
return mat_mul(b, c)
def check_rank_nullity(matrix):
"""True if rank + nullity = n and every null vector solves Ax = 0."""
basis = null_space(matrix)
solves = all(all(x == 0 for x in mat_vec(matrix, v)) for v in basis)
return solves and rank(matrix) + len(basis) == len(matrix[0])
def fmt(v):
"""Format a vector of fractions compactly."""
return "(" + ", ".join(str(x) for x in v) + ")"
def main():
a = [[1, 2, 1], [2, 4, 3]]
augmented = [[1, 2, 1, 4], [2, 4, 3, 9]]
reduced, pivots = rref(augmented)
print("Worked example: x + 2y + z = 4, 2x + 4y + 3z = 9")
print("RREF of the augmented matrix [A | b]:")
for row in reduced:
print(f" {fmt(row)}")
print(f"pivot columns {pivots}: x and z are pivots, y is free")
print(f"rank of A = {rank(a)}, nullity = {len(null_space(a))}, n = 3")
print("null space basis:", ", ".join(fmt(v) for v in null_space(a)))
print("so the solutions form the line (3, 0, 1) + t(-2, 1, 0).")
print()
rng = random.Random(2024)
trials, ok, exact_rank = 0, 0, 0
deficit = {}
for _ in range(300):
m, n = rng.randint(2, 6), rng.randint(2, 7)
r = rng.randint(1, min(m, n))
mat = random_matrix_of_rank(rng, m, n, r)
trials += 1
ok += check_rank_nullity(mat)
k = rank(mat)
exact_rank += k == r
deficit[r - k] = deficit.get(r - k, 0) + 1
print(f"Random integer matrices B*C of rank at most r: {trials}")
print(f" rank + nullity = n and A v = 0 checked: {ok} of {trials}")
print(f" rank came out exactly r: {exact_rank} of {trials}")
print(f" rank deficit r - rank -> count: {dict(sorted(deficit.items()))}")
print("A random product usually has full rank r; a deficit happens when")
print("the small random factors are accidentally dependent.")
print()
print("Epistemic status: exact rational arithmetic, so each case is a")
print("genuine check with no rounding; but 300 matrices are finitely many")
print("examples. Rank-nullity itself is proved in the lesson and in Lean.")
if __name__ == "__main__":
main()The second experiment asks how common diagonalisability is. For a real matrix the answer is decided by the discriminant of : positive gives two distinct real eigenvalues (diagonalisable over ), negative gives a pair of complex conjugate eigenvalues (diagonalisable over only), and zero gives a repeated eigenvalue , in which case is diagonalisable only if it already equals (if then ). It counts all 625 matrices with entries from to , then diagonalises the Fibonacci matrix symbolically.
"""Which 2 x 2 matrices can be diagonalised? An exhaustive count, and Fibonacci.
Part 1 classifies every 2 x 2 matrix with entries in {-2, ..., 2} (625 of
them) by its characteristic polynomial t^2 - (tr A) t + det A. Two distinct
real eigenvalues: diagonalisable over R. Non-real eigenvalues: diagonalisable
over C only. A repeated eigenvalue: diagonalisable only if A is already the
scalar matrix lambda I. Part 2 diagonalises the Fibonacci matrix with SymPy and
checks Binet's formula exactly for n <= 40. Part 3 shows SymPy's view of the
nilpotent matrix with rows (0, 1), (0, 0): one eigenvalue of algebraic
multiplicity 2 but only one independent eigenvector.
"""
import itertools
import sympy
def classify(a, b, c, d):
"""Classify [[a, b], [c, d]] by its eigenvalues.
Returns 'distinct real', 'complex', 'scalar' or 'defective'.
"""
trace, det = a + d, a * d - b * c
disc = trace * trace - 4 * det
if disc > 0:
return "distinct real"
if disc < 0:
return "complex"
return "scalar" if (b == 0 and c == 0 and a == d) else "defective"
def census(values):
"""Count the classes over all matrices with entries in ``values``."""
counts = {"distinct real": 0, "complex": 0, "scalar": 0, "defective": 0}
for a, b, c, d in itertools.product(values, repeat=4):
counts[classify(a, b, c, d)] += 1
return counts
def fibonacci(n):
"""F_0 = 0, F_1 = 1, F_{k+1} = F_k + F_{k-1}, by iteration."""
x, y = 0, 1
for _ in range(n):
x, y = y, x + y
return x
def binet(n):
"""(phi^n - psi^n) / sqrt(5) as an exact SymPy number."""
s5 = sympy.sqrt(5)
phi, psi = (1 + s5) / 2, (1 - s5) / 2
return sympy.expand((phi**n - psi**n) / s5)
def fibonacci_by_diagonalising(n):
"""The top-right entry of A^n = P D^n P^-1 for A = [[1, 1], [1, 0]]."""
p, d = sympy.Matrix([[1, 1], [1, 0]]).diagonalize()
power = p * sympy.diag(d[0, 0] ** n, d[1, 1] ** n) * p.inv()
return sympy.radsimp(sympy.expand(power[0, 1]))
def multiplicities(rows):
"""[(eigenvalue, algebraic, geometric)] for a SymPy matrix."""
return [(val, alg, len(vecs))
for val, alg, vecs in sympy.Matrix(rows).eigenvects()]
def main():
counts = census(range(-2, 3))
print("All 625 matrices [[a, b], [c, d]] with entries in -2..2:")
for label, count in counts.items():
print(f" {label:<14} {count:>4}")
print(" diagonalisable over R:", counts["distinct real"] + counts["scalar"])
print(" diagonalisable over C:", 625 - counts["defective"])
print()
p, d = sympy.Matrix([[1, 1], [1, 0]]).diagonalize()
print("Fibonacci matrix A = [[1, 1], [1, 0]] = P D P^-1 with")
print(" D =", list(d.diagonal()))
print(" A^n = P D^n P^-1, so F_n = (phi^n - psi^n) / sqrt 5")
ok = all(binet(n) == fibonacci(n) for n in range(41))
print(f" Binet's formula equals iteration for n = 0..40: {ok}")
print(f" F_40 from A^40 = P D^40 P^-1: {fibonacci_by_diagonalising(40)}")
print()
print("N = [[0, 1], [0, 0]]: (eigenvalue, algebraic, geometric) =",
multiplicities([[0, 1], [0, 0]]))
print("One independent eigenvector in a 2-dimensional space: N is not")
print("diagonalisable, exactly as the lesson (and Lean) proves.")
print()
print("Epistemic status: part 1 is an exhaustive check of 625 cases using")
print("the lesson's criterion; part 2 is exact symbolic arithmetic for")
print("n <= 40 only (the lesson proves Binet's formula for all n); part 3")
print("trusts SymPy's eigenvector routine, which agrees with the proof.")
if __name__ == "__main__":
main()Notice that the defective matrices are rare (56 of 625) — they satisfy the polynomial equation "discriminant " — while the matrices with complex eigenvalues are not rare at all: they fill an open region. The topologist's viewpoint below explains why this is the expected picture.
Explore: eigenvectors and the order of composition
The dashed lines are the eigenvector directions: the map slides points along them, stretching by the eigenvalue. Start from the symmetric matrix below (eigenvalues and , eigenvectors along and ), then try the shear (one invariant line only: defective) and the rotation (none).
Eigenvectors are invariant lines
Which presets have two invariant lines, one, or none?
- image of the grid
- image of the unit square
- image of the flag
- before the transformation
- invariant line
The columns of A are the images of e₁ = (1, 0) and e₂ = (0, 1): Ae₁ = (2, 1), Ae₂ = (1, 2)
det A = ad − bc = 3
The unit square (area 1) becomes a parallelogram of area |det A| = 3. Since det A > 0, orientation is preserved.
Invariant lines (real eigenvectors)
- λ₁ = 3, v₁ = (1, 1)
- λ₂ = 1, v₂ = (1, −1)
Vectors on the two dashed lines are only stretched, by the factors λ₁ = 3 and λ₂ = 1; every other direction is turned.
Composition: first a shear, then a quarter turn — or the other way round. The two results differ, which is the non-commutativity of matrix multiplication made visible.
AB is not BA
Apply A and then B, or B and then A, and compare the results.
- image of the grid
- image of the unit square
- image of the flag
- before the transformation
- after the first step
AB ≠ BA: the order matters.
BA means “apply A first, then B”: products of transformations are read from right to left.
det(AB) = det(BA) = det A · det B = 1 · 1 = 1 The area scale factor is the same in either order.
Exercises
1. Linear algebra
Warm-upHumanWhat is the rank of the matrix ?
2. Linear algebra
Warm-upHumanWhich of these are subspaces of the given vector space? (Choose all that apply.)
3. Linear algebra
CoreHumanA linear map is surjective. What is ?
4. Linear algebra
CoreHumanis a matrix with . What is ?
5. Linear algebra
CoreHumanWhich of these real matrices are diagonalisable over ? (Choose all that apply.)
6. Linear algebra
CoreHumanIn the proof that eigenvectors with distinct eigenvalues are independent, we reach for . Which fact lets us conclude ?
7. Linear algebra
StretchHumanFor a linear map we proved: if is finite-dimensional, then injective surjective. Which example shows that the finite-dimensionality hypothesis cannot be dropped?
8. Linear algebra
CoreFormalLet f : V →ₗ[K] W with [FiniteDimensional K V]. Which Lean statement correctly formalises the rank–nullity theorem?
9. Linear algebra
StretchComputationalWrite rank(rows) that returns the rank of a matrix (a list of rows of integers) by Gaussian elimination with exact Fraction arithmetic. Then use it to check rank–nullity on the photosynthesis matrix: its null space should be one-dimensional.
Common misconceptions
Misconception
"Matrix multiplication is commutative, like multiplying numbers." means "first , then ", and doing two transformations in the other order usually gives a different result: shear-then-rotate is not rotate-then-shear. Even when both and are defined they can differ, as and show. Some special families commute (diagonal matrices; rotations of the plane), and that is worth noticing when it happens.
Misconception
"Every square matrix is diagonalisable." is not, over any field: its only eigenvalue is and its eigenvectors fill only a line. Over , rotations are not diagonalisable either, for a different reason — no real eigenvalues. What is true: over , every matrix is similar to an upper triangular one, and to a Jordan normal form (see advanced linear algebra); and matrices with distinct eigenvalues are diagonalisable.
Misconception
"A linear map sends lines through the origin to lines." It sends them to lines or to the single point . The projection collapses the -axis. A linear map preserves lines exactly when it is injective, i.e. when its kernel is .
Misconception
"." The determinant is multiplicative, not additive: but for matrices. In general .
Misconception
"The zero vector is an eigenvector of every matrix." for every , which is exactly why eigenvectors are required to be non-zero — otherwise every scalar would be an "eigenvalue". (The eigenspace does contain .)
Misconception
"Vectors no two of which are parallel are independent." In , the vectors , and are pairwise non-parallel but dependent: the third is the sum of the first two. Independence is about the whole list, not pairs.
Many ways of seeing
Geometry— Linear maps are geometry: area, orientation, principal axes
For a linear map of and any region with a volume, ; the sign of says whether preserves or reverses orientation (the flag in the widget). The matrices preserving lengths are the orthogonal matrices, ; they have and in the plane they are exactly the rotations and reflections in lines through the origin. A real symmetric matrix () is always diagonalisable by an orthogonal matrix — the spectral theorem. Geometrically: the curve is a conic whose axes are the eigenvector directions of ; it is an ellipse when both eigenvalues are positive and a hyperbola when they have opposite signs. For instance has eigenvalues and , so it is an ellipse with semi-axes and along the eigenvectors and . See conic sections and, for Klein's view of geometry through groups of matrices, transformation geometry.
Topology— Two kinds of invertible matrix, and why generic matrices are diagonalisable
The set of invertible real matrices is an open subset of (it is where the continuous function is non-zero), and it has exactly two path components: and . One cannot continuously deform a reflection into the identity through invertible matrices, because along the path would have to pass through (intermediate value theorem). This is the topological meaning of orientation. By contrast is connected: the complex numbers form a connected set, and one can always steer around the zeros of .
Over , the matrices with distinct eigenvalues are those where the discriminant of — a polynomial in the entries — is non-zero; this set is open and dense, so every complex matrix is a limit of diagonalisable ones, and "being defective" is a closed condition of measure zero. The census in the computation section shows the shadow of this: defective matrices are rare. Over , however, the set with non-real eigenvalues is open too, so real diagonalisability is not generic. See matrix groups.
Analysis— The derivative is a linear map; infinite dimensions are different
Multivariable calculus is linear algebra applied locally: the derivative of at a point is the linear map that best approximates nearby, its matrix is the Jacobian, and the chain rule is the theorem "composition is matrix multiplication" (see multivariable calculus). The linear system of differential equations is solved by , and if then , so the eigenvalues decide stability: all real parts negative means every solution decays.
In infinite dimensions linear algebra becomes functional analysis, and some theorems change: the shift operator on sequences is injective but not surjective, so rank–nullity has no direct analogue, and an operator can have no eigenvalues at all while still having a "spectrum". Fourier series are coordinates with respect to the orthonormal basis of a space of functions (see functional analysis).
Algebra— Vector spaces are modules over a field — and fields are what make bases exist
Replace the field by a ring and the same axioms define an -module. Much of this lesson then breaks: the -module has no basis at all (every element satisfies , a non-trivial relation), and in the list is linearly independent but cannot be extended to a basis — the only bases of are and . The proofs of the exchange lemma and of the extension corollary divided by non-zero scalars — that is where fields are essential. Over a principal ideal domain such as there is a substitute, the Smith normal form, which classifies finitely generated abelian groups (see modules).
Algebra also asks which matrix identities hold universally. The Cayley–Hamilton theorem says : for the Fibonacci matrix, . And a representation of a group is a homomorphism — linear algebra used to study symmetry, which is the subject of representation theory.
Physics— Normal modes and quantum measurements are eigenvectors
Two equal masses joined to each other and to two walls by three equal springs (stiffness ) obey with . The eigenvectors of are (eigenvalue ) and (eigenvalue ): the normal modes, in which the masses swing together with frequency or against each other with frequency . Every motion is a superposition of the two — a change of basis to eigen-coordinates decouples the equations. The same mathematics describes molecular vibrations and the modes of a bridge.
In quantum mechanics a state is a vector in a complex vector space, a measurable quantity is a self-adjoint operator, and the possible results of a measurement are its eigenvalues — real, by the spectral theorem. The word "eigen" entered physics through this route (see quantum mechanics).
Category theory— Vect, and matrices as morphisms
Vector spaces over and linear maps form a category : composites of linear maps are linear and identities are linear (see categories). Choosing bases shows that the full subcategory of finite-dimensional spaces is equivalent to a strikingly simple category : its objects are the natural numbers , a morphism is an matrix, and composition is matrix multiplication. The theorem "composition is matrix multiplication" is precisely the statement that this is a functor, and invariance of dimension says that isomorphic objects of go to the same number. Change of basis is the freedom in choosing this equivalence.
History and global context
- China. Chapter 8 of The Nine Chapters on the Mathematical Art (compiled by about the 1st century CE), titled fangcheng ("rectangular arrays"), solves systems with as many as six unknowns by arranging the coefficients on a counting board and eliminating column by column — essentially Gaussian elimination, with negative numbers handled by coloured rods. Liu Hui's commentary (263 CE) explains the method.
- Japan and Europe, 1680s–1690s. Determinants appear independently in the work of Seki Takakazu (1683), in the context of eliminating unknowns from polynomial equations, and of Gottfried Wilhelm Leibniz (1693). Gabriel Cramer published his rule for solving square systems in 1750.
- Gauss used systematic elimination in his least-squares calculations of asteroid orbits in the early nineteenth century; the name "Gaussian elimination" is a later, Western attribution for a method known in China some 1,700 years earlier.
- The nineteenth century. Hermann Grassmann's Ausdehnungslehre (1844) developed linear combinations, independence and dimension in a geometric language that was decades ahead of its time. James Joseph Sylvester coined the word matrix (1850), and Arthur Cayley's Memoir on the theory of matrices (1858) introduced matrix algebra, including the Cayley–Hamilton theorem. Camille Jordan gave his normal form in 1870.
- Axioms. Giuseppe Peano gave an axiomatic definition of a vector space in 1888. The prefix eigen- ("own, characteristic") comes from David Hilbert's work on integral equations around 1904.
- Computation. Numerical linear algebra became a discipline with electronic computers; Alan Turing (1948) and James Wilkinson analysed rounding errors in elimination, and today large-scale eigenvector computations rank web pages and train machine-learning models.
Further reading
- Sheldon Axler, Linear Algebra Done Right (1996; 4th ed. 2024) — a clean, determinant-light treatment of vector spaces, linear maps and eigenvalues.
- Gilbert Strang, Introduction to Linear Algebra (1993; 6th ed. 2023) — matrices, elimination and applications, with a strong geometric and computational flavour.
- Paul R. Halmos, Finite-Dimensional Vector Spaces (1942; 2nd ed. 1958) — the classic coordinate-free account.
- Kenneth Hoffman and Ray Kunze, Linear Algebra (1961; 2nd ed. 1971) — thorough, including determinants and canonical forms.
- Lloyd N. Trefethen and David Bau, Numerical Linear Algebra (1997) — what happens to these algorithms on a real computer.