Contents / Linear Algebra / Orthogonality and Least Squares
Chapter 9
Orthogonality and Least Squares
Orthogonal sets, projections, Gram-Schmidt, QR, and least-squares fitting.
Introduction
Orthogonality is perpendicularity, freed from the plane. Two vectors in cannot be drawn, but the single equation still says everything a right angle ever said: the two directions carry independent information, and lengths add in the Pythagorean way. Almost every computation in this chapter is a consequence of that one equation.
The reason orthogonality earns a chapter of its own is that it turns hard problems into easy ones. Finding the coordinates of a vector in a general basis means solving a linear system; in an orthonormal basis each coordinate is one dot product. Finding the point of a subspace closest to a given vector looks like a minimisation problem in infinitely many candidates; orthogonality reduces it to a single matrix equation. And when a system has no solution at all — the normal situation when there is more data than there are unknowns — orthogonality produces the next best thing: the vector that makes as small as possible. That is the least-squares problem, and it is the computational heart of statistics, signal processing, and every kind of curve fitting.
The chapter runs in the order the ideas depend on one another: the dot product and length; orthogonal complements and the four fundamental subspaces; orthogonal and orthonormal sets; orthogonal projection and the matrix that performs it; the Gram–Schmidt process, which manufactures orthonormal bases on demand; the factorization that Gram–Schmidt secretly computes; least squares and the normal equations; and finally linear models, where all of it is applied to data.
Everything here happens in with the ordinary dot product. The chapter Inner Product Spaces takes the same definitions and replaces the dot product by an abstract inner product, so that functions and polynomials acquire lengths and angles too; nothing in this chapter has to be relearned there, only reread.
9.1The dot product, length, and orthogonality
Everything begins with one operation that eats two vectors and returns a number.
Definition 9.1 (Dot product). For written as column vectors, the dot product (or inner product) is the scalar
Reading as the matrix product — a matrix times an matrix — is not a cosmetic rewriting. It is what lets us move dot products through matrices: . That identity,
is used in almost every proof in this chapter, and it is the reason the transpose appears wherever orthogonality does.
Proposition 9.2 (Algebraic properties of the dot product). For all and all scalars :
- (symmetry);
- and (linearity in each slot);
- , with equality if and only if (positive definiteness).
Proof. Properties 1 and 2 are immediate from the formula , since multiplication of real numbers is commutative and the sum is linear in each factor. For 3, is a sum of squares, hence ; and a sum of squares of real numbers vanishes exactly when every term vanishes, i.e. when every .∎
Property 3 is the one that does the real work, and it is worth noticing how little it would take to lose it. If we had defined , symmetry and linearity would survive but would have "length zero" while being a nonzero vector, and the whole geometry of the chapter would collapse. Positive definiteness is what allows a dot product to define a length.
Definition 9.3 (Length, unit vector, distance). The length (or norm) of is
A vector with is a unit vector. Normalising a nonzero means replacing it by . The distance between and is .
Note that , with the absolute value: scaling by triples the length and does not negate it. In particular really is a unit vector, since its length is , and it points the same way as .
Theorem 9.4 (Cauchy–Schwarz inequality). For all ,
with equality if and only if and are parallel (one is a scalar multiple of the other).
Proof. If both sides are and the vectors are trivially parallel, so assume and set . By positive definiteness,
Substituting the chosen , the last two terms combine:
Multiplying by gives , and taking square roots gives the inequality. Equality forces , hence by positive definiteness; conversely if then both sides equal .∎
Because , the quotient always lies in , so there is exactly one angle with
This defines the angle between two vectors in ; in and it agrees with the angle you would measure with a protractor. The case is the case , which is where the chapter's subject begins.
Theorem 9.5 (Triangle inequality). For all , .
Proof. Expand and apply Cauchy–Schwarz to the cross term:
Both sides are non-negative, so taking square roots preserves the inequality.∎
Definition 9.6 (Orthogonal vectors). Two vectors are orthogonal, written , if .
The zero vector is orthogonal to everything, which is a convention rather than a discovery, but a convenient one: it makes "the set of vectors orthogonal to " a subspace rather than a subspace with a hole at the origin.
Theorem 9.7 (Pythagorean theorem in ). if and only if .
Proof. Expanding as in the previous proof,
So the claimed identity holds exactly when the cross term is zero, i.e. exactly when .∎
The "if and only if" is worth pausing on. Pythagoras is not merely a consequence of perpendicularity in ; it is equivalent to it. That makes it a usable test: if you compute the three lengths and they satisfy the identity, you have proved a right angle without ever computing the dot product.
Intuition. Think of two people pulling a crate, one due north with force and one due east with force . Because the directions are perpendicular, neither pull helps or hinders the other, and the net force has magnitude . If instead they both pull roughly north-east, their efforts overlap: the same and produce a net force close to . The dot product measures exactly that overlap, and it is zero precisely when the efforts are independent.
Example 9.8 (Lengths, distance, and an angle). For and , compute , , and the angle between them.
Solution. The length is , and likewise .
For the distance, , so
The dot product is , so
and radians, about .
Sanity check with Cauchy–Schwarz: , comfortably. And since is positive but well below , the vectors should point broadly the same way without being parallel — which matches .□
Example 9.9 (Building a unit vector and testing orthogonality). Normalise , and decide whether is orthogonal to .
Solution. First the length: , so and the unit vector is
Check: ✓.
Now the test. , so they are not orthogonal. A second check confirms it: , while . The two disagree by exactly , as the expansion predicts.□
Example 9.10 (Forcing orthogonality by choosing a parameter). Find all for which is orthogonal to .
Solution. Write the condition out:
So exactly when , i.e. .
Check at : , , and their dot product is ✓. Notice how quickly the answer came: orthogonality is one scalar equation, so imposing it on a one-parameter family generically leaves finitely many solutions.□
Pitfall. is not the Pythagorean theorem and is almost never true — it holds only when and point in the same direction. The Pythagorean identity is about the squares of the lengths. Squaring is not optional.
9.2Orthogonal complements and the four fundamental subspaces
A single orthogonality condition is a fact about two vectors. The useful object is the set of all vectors orthogonal to a whole subspace at once.
Definition 9.11 (Orthogonal complement). Let be a subspace of . Its orthogonal complement is
read " perp".
Proposition 9.12 ( is a subspace, and testing it is finite). For any subspace , is a subspace of . Moreover, if , then
Proof. The zero vector is orthogonal to everything, so . If and is a scalar, then for every ,
so is closed under addition and scalar multiplication.
For the second claim, one direction is trivial since each . Conversely, suppose for every . A general is , so by linearity
The second half of that proposition is what makes orthogonal complements computable. The definition quantifies over infinitely many ; the proposition says you only ever have to test a spanning set. Concretely, if the are the rows of a matrix , then " is orthogonal to every row" is the single matrix equation — and that is the whole content of the next theorem.
Theorem 9.13 (The fundamental orthogonality relations). For any matrix ,
Proof. The -th entry of the vector is the dot product of the -th row of with . Hence says precisely that is orthogonal to every row of , which by the previous proposition says precisely that . That is the first relation.
Apply the first relation to in place of : . Since the rows of are the columns of , , giving the second relation.∎
Theorem 9.14 (Dimensions of complementary subspaces). If is a subspace of , then
Proof. For the intersection: if then is orthogonal to itself, so , and positive definiteness forces .
For the dimension count, choose a basis of and let be the matrix whose rows are those basis vectors, where . Then and , and by the theorem above . The Rank–Nullity Theorem for gives , i.e. .
Finally, every is orthogonal to every element of by definition, so . Applying the dimension count twice, . A subspace contained in another of the same finite dimension equals it, so .∎
Collecting these for a single matrix produces the picture Strang calls the fundamental theorem of linear algebra. Let be of rank . Four subspaces appear: and live in the domain , while and live in the codomain .
Summary (The four fundamental subspaces). For an matrix of rank :
with inside and inside . In each space the two subspaces are orthogonal complements, so their dimensions add to the dimension of the ambient space.
Intuition. Picture as a machine that takes vectors from to . The domain splits cleanly into two perpendicular halves: the null space, which the machine crushes to zero, and the row space, which it maps one-to-one onto the column space. Nothing in the row space is wasted and nothing in the null space survives. On the other side, the column space is everything the machine can reach, and the left null space is the perpendicular part of it can never touch — which is exactly why an inconsistent system is inconsistent: has a component in that unreachable direction.
Example 9.15 (Computing an orthogonal complement). Let . Find a basis for and confirm the dimension count.
Solution. By the finite test, lies in exactly when
This is one equation in three unknowns, so and are free and . Then
so spans , and the two vectors are not multiples of each other, hence form a basis.
Check: ✓, and each basis vector dots to and against ✓. Geometrically is a line through the origin and is the plane perpendicular to it.□
Example 9.16 (All four subspaces of one matrix). For
find the dimensions of all four fundamental subspaces and a basis for .
Solution. Row reduce: the second row is twice the first, so reduces to and . Here , , so
For , solve with ; all three equations read , , , which is the single condition . A basis is , matching ✓.
Sanity check the orthogonality: is spanned by , and ✓. So , which has a nonzero component along , makes inconsistent — exactly the situation least squares was invented for.□
Pitfall. is not "the vectors left over" or "the complementary coordinates". It is defined by an orthogonality condition, and it depends on the dot product, not on how you happened to write the vectors. Two subspaces can satisfy and without being — the -axis and the line in are such a pair.
9.3Orthogonal and orthonormal sets
A basis is useful; an orthogonal basis is useful and cheap.
Definition 9.17 (Orthogonal and orthonormal sets). A set is orthogonal if whenever . It is orthonormal if in addition for every ; equivalently,
An orthogonal basis for a subspace is a basis of that is an orthogonal set; an orthonormal basis is one that is orthonormal.
Theorem 9.18 (Orthogonal sets are linearly independent). Every orthogonal set of nonzero vectors in is linearly independent.
Proof. Let be orthogonal with every , and suppose
Fix an index and take the dot product of both sides with . On the right we get . On the left, linearity gives , and every term with vanishes by orthogonality. What survives is
Since we have , so . As was arbitrary, all coefficients vanish and the set is independent.∎
The hypothesis "nonzero" cannot be dropped: is an orthogonal set, since , and it is dependent. Apart from that one degenerate case, orthogonality is a strictly stronger condition than independence and it is far easier to check — dot products rather than a row reduction.
The real payoff is that coordinates become free.
Theorem 9.19 (Coefficients in an orthogonal basis). Let be an orthogonal basis for a subspace . Every has the unique expansion
If the basis is orthonormal the denominators are and .
Proof. Since the set is a basis of , such an expansion exists and is unique; the only question is what the coefficients are. Dot both sides with . As in the previous proof every cross term dies, leaving
Dividing by gives the formula.∎
Compare the cost. In a general basis, finding coordinates means solving a linear system — and if you later add a -st basis vector, every old coordinate changes and you start again. In an orthogonal basis each coefficient is computed by one dot product, independently of all the others, and adding a new orthogonal vector leaves the old coefficients untouched. That independence is the reason Fourier series, wavelets, and principal components are all built on orthogonal bases.
Intuition. An orthogonal basis is a set of measuring instruments that do not interfere. Asking "how much north?" and "how much east?" can be done in either order with the same answers. In a skewed basis the questions are entangled: how much of the first direction you need depends on how much of the second you took, so you must solve for all of them at once.
Matrices whose columns are orthonormal deserve their own name, because the condition has a compact matrix form.
Theorem 9.20 (Matrices with orthonormal columns). Let be an matrix. Its columns are orthonormal if and only if
When this holds, for all :
In particular if and only if : multiplication by preserves lengths and angles.
Proof. Write . The entry of is the -th row of times the -th column of , that is . So says exactly that these dot products are on the diagonal and off it, which is orthonormality.
Given , compute the inner product directly:
Taking gives , and lengths are non-negative, so . The statement about orthogonality is the case where one side is zero.∎
Definition 9.21 (Orthogonal matrix). An orthogonal matrix is a square matrix whose columns are orthonormal; equivalently , equivalently .
The word is a historical misnomer — such a matrix ought to be called orthonormal — but it is universal, so it is worth stating the traps plainly. A non-square matrix with orthonormal columns satisfies but not ; only in the square case does force , and then the rows are orthonormal as well.
Corollary 9.22 (Determinant and eigenvalues of an orthogonal matrix). If is orthogonal then , and every real eigenvalue of is .
Proof. From , take determinants: . Since , this gives , so .
If with and real, then length preservation gives . Dividing by gives , so .∎
(The same argument applied to complex eigenvalues shows every eigenvalue of an orthogonal matrix has modulus ; a rotation by in has eigenvalues and no real eigenvalues at all.)
Example 9.23 (Verifying an orthogonal basis and reading off coordinates). Show that , , is an orthogonal basis of , and express in it.
Solution. Three dot products settle orthogonality:
All three vectors are nonzero, so by the independence theorem they are independent; three independent vectors in form a basis.
Now the coefficients. The norms squared are , , . The numerators are
Hence , , , and
Check by recomputing: ✓. Notice that no linear system was solved.□
Example 9.24 (A matrix with orthonormal columns). Let
Verify , compute for , and explain why .
Solution. The columns have squared lengths and , and their dot product is
so ✓.
Length preservation gives without computing . (If you want the check: , whose squared length is ✓.)
Finally, is but , so is singular and cannot be . In fact is the matrix that projects onto the plane spanned by the columns of — the subject of the next section.□
Pitfall. The formula with no denominator is for orthonormal bases only. With merely orthogonal vectors you must divide by . Forgetting the denominator scales every coordinate by the wrong factor and is the single most common error in this chapter.
9.4Orthogonal projection
We can now answer the question that motivates the rest of the chapter: given a subspace and a vector outside it, what is the point of closest to ?
Theorem 9.25 (Orthogonal Decomposition Theorem). Let be a subspace of . Every can be written in exactly one way as
If is any orthogonal basis of , then
The vector is called the orthogonal projection of onto , written .
Proof. Existence. Every subspace of has an orthogonal basis — the Gram–Schmidt process constructs one from any basis, as the next section shows — so fix one, , and define by the displayed formula and . Then , being a combination of the . To see it suffices, by the finite test, to check for each . Dotting the formula with kills every term but the -th:
so .
Uniqueness. Suppose with and . Then
The left side lies in and the right side lies in , so the common value lies in . Hence and .∎
Uniqueness has a consequence worth stating: although the formula for mentions a particular orthogonal basis, the answer does not depend on which one you chose. Two different orthogonal bases of give the same projection, because both produce a decomposition of the required form and there is only one.
The simplest case is a line, with , where the sum has one term:
The fraction is a scalar — how much of lies along , measured in units of — and multiplying by turns it back into a vector. The related quantity is the scalar projection, the signed length of .
Theorem 9.26 (Best Approximation Theorem). Let be a subspace of , let , and let . Then for every with ,
So is the unique closest point of to , and .
Proof. Split the error through :
The first piece lies in by the decomposition theorem; the second lies in , since and both do. So the two pieces are orthogonal and Pythagoras applies:
If the last term is strictly positive, so , and taking square roots gives the strict inequality.∎
That proof is the whole of least squares in three lines, and it is worth seeing what it depends on. It needs only that the error is perpendicular to . Any other candidate is penalised by the extra leg , which is a squared length and therefore cannot help. Minimising a distance has been converted into satisfying an orthogonality condition, and orthogonality conditions are linear equations.
Intuition. Stand on a ladder above a flat floor. Your shadow with the sun straight overhead is the point of the floor nearest your feet, and the line from shadow to foot is vertical — perpendicular to the floor. Walk your shadow anywhere else on the floor and you have added a horizontal leg to a right triangle whose vertical leg has not changed, so the distance can only grow. The Best Approximation Theorem is that right triangle.
Now we build the matrix that performs a projection. Suppose the columns of an matrix form a basis for — not necessarily orthogonal. Then means for some , and the orthogonality of the error says , i.e.
To solve for we need to be invertible, which is exactly what independent columns buy us.
Lemma 9.27 (Invertibility of ). For an matrix , the matrix is invertible if and only if the columns of are linearly independent. In that case is symmetric and positive definite.
Proof. First, . Indeed if then certainly . Conversely if , multiply on the left by :
so by positive definiteness.
Now is a square matrix, so it is invertible if and only if its null space is trivial, if and only if , if and only if the columns of are independent. Symmetry is . Positive definiteness follows from the same computation: for , because .∎
Theorem 9.28 (The projection matrix). Let the columns of the matrix be a basis for . Then for every ,
If the columns of are orthonormal — write — this simplifies to , and for a single unit vector to the rank-one matrix .
Proof. By the lemma is invertible, so the derivation above solves to give and hence . To confirm this is the projection, note and
so every column of , i.e. . By uniqueness in the Orthogonal Decomposition Theorem, .
When the columns are orthonormal, , so and .∎
Theorem 9.29 (Projection matrices are exactly the symmetric idempotents). A matrix of size satisfies
if and only if is the orthogonal projection onto the subspace . In that case is the orthogonal projection onto .
Proof. ( for the formula.) If , write , which is symmetric because is. Then
and
since .
(.) Suppose , and let . Given any , write . The first term is in by definition. For the second, take any , say ; then
using symmetry in the second step and idempotence in the fourth. So , and this is the decomposition of the Orthogonal Decomposition Theorem; by its uniqueness, . The same display shows is symmetric and idempotent with column space , so it projects onto .∎
Both hypotheses are needed. The matrix is idempotent but not symmetric: it is a projection onto the -axis, but along the line rather than perpendicularly, and it is not distance-minimising. Symmetry is what makes a projection orthogonal.
Example 9.30 (Projecting onto a plane using an orthogonal basis). Let with and (this is the -plane). Project onto and find the distance from to .
Solution. The basis is orthogonal: ✓. Both have , and
So
The error is , and .
Two checks. First, and ✓. Second, Pythagoras: should equal ✓. And the answer is obviously right geometrically: projecting onto the -plane deletes the -coordinate.□
Example 9.31 (A projection matrix from a non-orthogonal basis). Let , whose columns are independent but not orthogonal. Compute and use it to project onto .
Solution. First , with determinant , so
Next , and multiplying by gives
Then is the first column of :
Checks. The trace of is , as it must be for a projection matrix (a projection's eigenvalues are with multiplicity and otherwise). is visibly symmetric. And the error dots to against the first column of and against the second ✓.□
Example 9.32 (Distance from a point to a plane through the origin). Find the distance from to the plane .
Solution. Rather than find a basis for the plane, project onto its orthogonal complement: is the line spanned by the normal , and the component of in is the error . So
and the distance is
As a by-product , which indeed satisfies ✓. Projecting onto the complement is almost always the cheaper route when .□
Pitfall. The formula requires the columns of to be a basis for — independent. If you include a redundant spanning vector, is singular and the formula is meaningless. And do not "simplify" to : is not square, so does not exist.
9.5The Gram–Schmidt process
Orthogonal bases make everything easy, but subspaces do not arrive equipped with one. Gram–Schmidt manufactures one, and it does so by using the only tool we have: projection.
Suppose is a basis for . Take ; there is nothing yet to be orthogonal to. For we want a vector in that is orthogonal to . Write as its component along plus what is left over; the leftover is exactly what we want:
At the -th step the same idea applies with : subtract from its projection onto everything already built.
Method 9.33 (The Gram–Schmidt process). Given a basis of , set and, for ,
Then is an orthogonal basis of . To obtain an orthonormal basis, normalise at the end:
Theorem 9.34 (Correctness of Gram–Schmidt). With the notation of the recipe, for each :
- ;
- is orthogonal to ;
- .
Consequently is an orthogonal basis of , and the normalised is an orthonormal basis of .
Proof. Induction on . For all three claims are clear: since it belongs to a basis, claim 2 is vacuous, and claim 3 is an identity.
Assume the claims for all indices below . By the inductive hypothesis is an orthogonal set of nonzero vectors spanning , hence an orthogonal basis of it. The sum subtracted in the recipe is therefore exactly , by the Orthogonal Decomposition Theorem, and so
which gives claim 2.
For claim 1: if then , contradicting the linear independence of the .
For claim 3: is plus a combination of , all of which lie in ; hence and the left span is contained in the right. Rearranging the recipe as gives the reverse containment. Both spans then have the same dimension and one contains the other, so they are equal.
Finally, the are pairwise orthogonal and nonzero, hence independent, and there are of them inside : an orthogonal basis. Normalising rescales each by a positive number, which changes neither orthogonality nor the span, and makes each length .∎
Two remarks on the recipe. First, the projections are subtracted from the original , not from a partially updated vector, and they use all previous , not just . Second, it is almost always easier to postpone normalising: dividing by early introduces square roots into every subsequent arithmetic step, and since the recipe's denominators handle the scaling automatically, nothing is gained. You may also rescale any by a nonzero constant to clear fractions before continuing — the span and the orthogonality are unaffected.
Intuition. Gram–Schmidt builds a coordinate frame one axis at a time, like squaring up a crooked room. The first wall you simply accept as a reference direction. For the second wall you take the crooked one and shave off however much of it points along the first — what remains is genuinely perpendicular. For the third you shave off its overlap with both finished walls. Each vector keeps whatever part of it is new and surrenders whatever part was already accounted for.
Example 9.35 (Gram–Schmidt on two vectors). Find an orthogonal basis and then an orthonormal basis for , where and .
Solution. Set . Then and , so
Check: ✓. An orthogonal basis is , or more simply after rescaling.
Normalising: and , so
Check ✓ and ✓. Span preserved: , so nothing was lost.□
Example 9.36 (Gram–Schmidt on three vectors). Apply Gram–Schmidt to , , in .
Solution. Step 1: , with .
Step 2: , so
Rescale by to , which is legitimate and keeps the arithmetic in integers. Then .
Step 3: and , so
Adding componentwise, , which rescales to .
Checks: ✓ and ✓. Normalised, the orthonormal basis is
Remark (Classical versus modified Gram–Schmidt). The recipe as written is classical Gram–Schmidt, and in exact arithmetic it is correct. In floating point it is not to be trusted. When the are nearly dependent, is a small difference of large vectors, rounding errors are amplified by the cancellation, and the computed vectors drift out of orthogonality — sometimes catastrophically.
Modified Gram–Schmidt fixes most of this by subtracting one projection at a time and updating as it goes:
Mathematically the two produce the same answer — each projection is taken against an already-orthogonal — but numerically the modified version measures each overlap against the current partially-orthogonalised vector, so an error made at step is corrected at step instead of compounding.
Serious software does neither. LAPACK computes by Householder reflections: instead of building orthogonal vectors, it applies a sequence of orthogonal reflection matrices that zero out the entries below the diagonal of one column at a time. Because every step is an exactly orthogonal transformation, the computed is orthogonal to machine precision no matter how ill-conditioned is. Gram–Schmidt remains the right way to understand orthogonalisation, and the wrong way to implement it.
Pitfall. Gram–Schmidt depends on the order of the input vectors: reordering generally produces a different orthonormal basis, and is always a multiple of . So "find the orthonormal basis" is never a well-posed question; the order must be specified. The subspace spanned is of course the same either way.
9.6The factorization
Gram–Schmidt does more than produce an orthonormal basis: it records, in its own coefficients, how to rebuild the original vectors. Collecting those coefficients into a matrix gives one of the two or three most important factorizations in numerical linear algebra.
Theorem 9.37 ( factorization). Let be an matrix with linearly independent columns. Then can be written
where is with orthonormal columns (so ) and is , upper triangular, with strictly positive diagonal entries. Moreover , and the factorization with positive diagonal is unique.
Proof. Existence. Let be the columns of and run Gram–Schmidt to get the orthonormal ; set . By claim 3 of the correctness theorem, , so by the orthonormal coefficient formula
with no for . Define for and for ; then is upper triangular and the display says exactly that the -th column of equals times the -th column of , i.e. .
The diagonal entry is . Since and is orthogonal to ,
Finally .
Uniqueness. Suppose with both factorizations of the stated form. Then . Call this matrix . The right-hand side is a product of upper triangular matrices with positive diagonals, hence upper triangular with positive diagonal. The left-hand side satisfies
and from we get . So is an orthogonal matrix that is upper triangular with positive diagonal. Its first column is a unit vector whose only possibly nonzero entry is , so ; then orthogonality of the second column to the first forces , and being a unit vector forces ; continuing down the columns gives . Hence and .∎
So costs nothing extra: its entries are the very dot products Gram–Schmidt already computed. The diagonal measures how much genuinely new direction contributed, and a tiny is the signal that the columns of are nearly dependent.
Example 9.38 (Computing and explicitly). Find the factorization of
Solution. Columns: , .
Gram–Schmidt. , , so . Next and , so
with . Dividing,
Now entry by entry:
and . So
Check ✓ and ✓, both positive as the theorem promises. Verify one entry of : the entry is ✓, matching .□
Example 9.39 (Reading off the Gram–Schmidt arithmetic). In the previous example, obtain without computing any new dot products.
Solution. Gram–Schmidt already produced everything. The diagonal entries are the lengths of the un-normalised vectors: and . The off-diagonal entry is the coefficient by which was subtracted, rescaled to match : we had
so ✓, agreeing with the direct computation. In general, if step of Gram–Schmidt subtracted , then and . The whole of is a bookkeeping record of the orthogonalisation.□
Pitfall. is not an orthogonal matrix unless is square. For , is and satisfies , but — indeed is the projection matrix onto . Writing for a tall is a common and fatal slip.
9.7Least-squares problems
An overdetermined system — more equations than unknowns — almost never has a solution. Geometrically, is solvable exactly when , and when is with , is a low-dimensional subspace of that a measured will miss. Declaring defeat is not an option when the equations come from data, so we change the question.
Definition 9.40 (Least-squares solution). Let be and . A least-squares solution of is a vector such that
The vector is the residual, and is the least-squares error.
The name comes from the fact that minimising is the same as minimising its square, — a sum of squared errors. Squaring is not merely convenient: it makes the objective a differentiable quadratic, which is why the answer is a linear system rather than something harder.
Theorem 9.41 (The normal equations). The set of least-squares solutions of is exactly the solution set of
This system is always consistent. If the columns of are linearly independent, is invertible and the least-squares solution is unique:
Proof. By projection. As ranges over , ranges over all of . By the Best Approximation Theorem the quantity is smallest exactly when . That equation is consistent because , so least-squares solutions exist. And holds if and only if , which says
i.e. .
By calculus. Let . Expanding,
using (a matrix equals its transpose). The gradient of the quadratic form with symmetric is , and the gradient of the linear term is , so
Setting gives the normal equations. Because is positive semidefinite, is convex and every critical point is a global minimum, so the condition is sufficient as well as necessary.
Uniqueness. By the lemma on , independent columns make invertible, and the displayed formula follows.∎
The two derivations illuminate different things. The projection argument explains why the answer is what it is — the residual must be perpendicular to everything the model can produce, otherwise you could still improve the fit by moving in that direction. The calculus argument explains why nothing worse than a linear system appears: the objective is a quadratic, and quadratics have linear gradients. In statistics the first is the geometric picture of regression and the second is the derivation you find in a textbook; they are the same theorem.
Intuition. You are trying to reach a target but your controls only let you move within a plane . Least squares says: go to the point of the plane directly beneath the target. You know you are there when the remaining gap points straight out of the plane — if the gap had any sideways component, sliding that way would shorten it. "The residual is orthogonal to every column of " is precisely the statement that nothing sideways is left, and written out it is .
Once is known, the error can be computed directly as , but there is a shortcut worth knowing. Since with , Pythagoras gives
This identity is the linear-algebra form of the statistician's "total sum of squares = explained + residual".
Method 9.42 (Solving a least-squares problem). To find the least-squares solution of :
- Form and .
- Solve by row reduction (or by the inverse, for ).
- Compute the residual and the error .
- Check: should be .
Alternatively, if is available, substitute: the normal equations become , and since and is invertible we may cancel to get
a triangular system solved by back-substitution. This is how least squares is actually computed. Forming squares the condition number of the problem — the numerical difficulty roughly doubles in exponent — while the route never forms at all.
Example 9.43 (A least-squares solution and its error). Find the least-squares solution of and the least-squares error, where
Solution. The system is inconsistent: the third equation would need while the first two give .
Form the normal equations. and .
Solve: by symmetry with , so
Residual: , so and
Checks. ✓. And the Pythagorean shortcut: , , and ✓.□
Example 9.44 (Least squares with dependent columns). Find all least-squares solutions of for
Solution. The columns are identical, so they are dependent and will be singular. Compute anyway: and .
The normal equations reduce to the single equation , i.e. . The solution set is the line
So there are infinitely many least-squares solutions — but they all give the same prediction: for every , because the added vector lies in . The projection is unique even when is not.
Check: and ✓. The error is . Note is the average of the data repeated — fitting a constant to returns their mean , exactly as least squares should.□
Example 9.45 (Least squares via ). Use the factorization from the earlier example, with
to find .
Solution. From before, , , and .
Compute .
Back-substitute in . The second row gives , so
The first row gives , so and .
Check against the normal equations: , , and indeed ✓. Only back-substitution was needed, and never appeared.□
Remark (The pseudoinverse). When has independent columns, the map is given by the matrix
called the pseudoinverse of . It satisfies and , the projection onto , so it inverts as far as anything can. When the columns are dependent this formula fails, but a pseudoinverse still exists and still picks out a canonical least-squares solution — the one of smallest norm. Constructing it requires the singular value decomposition, and it is treated in the chapter Singular Value Decomposition.
Pitfall. A least-squares solution does not satisfy , and checking it by substituting back into the original system will always look like failure. The correct check is . Relatedly, the normal equations are — both sides get multiplied by .
9.8Applications to linear models
The reason least squares appears in every quantitative field is that "fit a model to data" is nearly always an overdetermined linear system in disguise. The trick is always the same: the unknowns are the parameters, and the data supply the rows.
Definition 9.46 (Design matrix and linear model). A linear model predicts observations by
where (the design matrix) has one row per observation and one column per parameter, is the parameter vector, and is the residual. The least-squares estimate solves .
"Linear" refers to linearity in the parameters, not in the data. Fitting is a linear model, because the unknowns enter linearly; the columns of just happen to be , , and . Fitting is not, because sits in an exponent. This is why one method covers lines, polynomials, planes, sinusoids of known frequency, and much else.
For a line through points , the design matrix and its normal equations are
Solving the system gives the familiar regression formulas
The first row of says : a fitted line with an intercept always has residuals summing to zero. The second row says . Those two identities are free diagnostics.
For a quadratic the design matrix gains a column of ; for a degree- polynomial it is the Vandermonde matrix with columns . For a plane fitted to points , the columns are , and . Nothing in the method changes; only the columns do.
Definition 9.47 (Weighted least squares). If observation deserves weight , the weighted least-squares estimate minimises
Proposition 9.48 (Weighted normal equations). The weighted least-squares estimate is exactly the solution set of
Proof. Apply the ordinary normal equations to the rescaled problem , whose residual norm is exactly the weighted objective. They read , and since is diagonal, , giving .∎
Weights are how you tell the fit which data to trust. A measurement with standard deviation is conventionally given weight , so precise observations pull the fit harder and noisy ones are allowed to miss. Setting some removes that observation entirely — a useful way to think about what a weight does.
Intuition. Ordinary least squares treats every data point as an equally strong spring pulling the fitted curve towards it, and the curve settles where the spring forces balance. Weighted least squares makes some springs stiffer. A point with weight pulls as hard as nine equally-placed unweighted points, because the objective squares the weight.
Example 9.49 (Fitting a line). Fit to by least squares, and report the least-squares error.
Solution. Here , , , , . So
The determinant is , so
The fitted line is .
Residuals: the predictions are , so and
Checks: ✓ and ✓.□
Example 9.50 (Fitting a parabola). Fit to the four points .
Solution. The design matrix and its products are
where the entries of are , , , , , and collects , , .
Now solve , i.e.
Halve the first equation to and subtract it from the second: . Multiply that halved equation by and subtract from the third: . Subtracting the two results gives , so ; then gives , and finally , so .
The fitted parabola is
Check the first normal equation: ✓. Third: ✓.□
Example 9.51 (Weighted least squares). Fit a constant to the observations with weights .
Solution. Here and , so and
Hence .
Compare with the unweighted answer, which is the plain mean . The heavily weighted second observation has pulled the estimate from most of the way to , as it should: the second point counts nine times as much as the first. In general, fitting a constant by weighted least squares returns the weighted mean ✓.□
Pitfall. The design matrix has one column per parameter and one row per data point, not the other way round. If you are fitting three coefficients to twenty points, is , is , and the normal equations are a small system no matter how much data you have. Building a matrix means you have transposed the model.
- Confusing orthogonal with orthonormal. Orthogonal means pairwise perpendicular; orthonormal adds unit length. The shortcut and the shortcut both require orthonormality. With a merely orthogonal basis you must divide by .
- Calling a tall matrix with orthonormal columns "orthogonal". always holds; holds only when is square. For tall , is a projection matrix, not the identity, and does not exist.
- Dropping terms in Gram–Schmidt. Each must have its projection onto *every* earlier removed, not just the most recent one, and the projections are subtracted from the original .
- Expecting Gram–Schmidt to have a unique answer. The output depends on the order of the input vectors and on the sign convention; only the span is order-independent.
- Writing the normal equations wrongly. They are . Not , and not .
- **Using without checking rank.** is invertible if and only if the columns of are independent. With dependent columns, least-squares solutions still exist — infinitely many of them — but the inverse formula does not apply.
- **Verifying a least-squares solution by substituting into . ** It will not satisfy it; that was the point. Check instead.
- Forgetting that the error is a length, not a squared length. The least-squares *error* is ; the quantity being minimised is its square. Reporting one for the other is a very common off-by-a-square-root.
- **Assuming is whatever coordinates does not use.** It is defined by dot products with all of ; compute it as the null space of a matrix whose rows span .