Foundations to FrontierPart VII: Applied mathematics and computationBezhig

A02: Orthogonality, least squares, eigenvectors, and SVD

5 exercises, each with a complete solution. 1 figure. 1 code listing. 1 note from the engine.

On this page
  1. A. Prerequisites and observable goals
  2. B. The central question: what is the best achievable approximation?
  3. C. Deriving projection rather than memorizing it
  4. D. Least squares is projection onto the column space
  5. E. Eigenvectors identify directions preserved by a square map
  6. F. Singular values separate rotations from stretching
  7. G. Independent practice
  8. H. Complete solutions: A02
  9. I. Retention and readiness

A. Prerequisites and observable goals#

Before

A01: matrices, bases, rank, and linear maps. Derivatives from Calculus I help with the optimization interpretation but are not needed for the projection construction.

After

Project onto a subspace, derive least squares from residual orthogonality, compute a small eigendecomposition, recognize positive definiteness, and interpret singular values geometrically.

Level: Degree core with an introductory bridge to advanced numerical linear algebra.

B. The central question: what is the best achievable approximation?#

A system Ax=bAx=b may have no exact solution. Measurements contain noise, and a simple model may not represent every observed outcome. Rather than inventing an exact solution, choose xx that minimizes a specified discrepancy. Ordinary least squares minimizes ∥Ax−b∥22\|Ax-b\|_2^2, the sum of squared coordinate residuals. This is a modeling decision: large residuals receive disproportionate weight, units matter, and outliers may dominate. It is not automatically the right loss for every application.

The dot product uTv=∑iuiviu^Tv=\sum_i u_iv_i measures alignment in Euclidean coordinates. The norm ∥u∥2=uTu\|u\|_2=\sqrt{u^Tu} measures length. Nonzero vectors are orthogonal when their dot product is zero. An orthonormal collection has unit-length, mutually orthogonal vectors. These properties simplify coordinates because the coefficient of bb along a unit vector qq is simply qTbq^Tb.

C. Deriving projection rather than memorizing it#

To approximate bb by a multiple cucu of a nonzero vector uu, require the leftover b−cub-cu to be perpendicular to uu:

uT(b−cu)=0⟹c=uTbuTu.u^T(b-cu)=0\quad\Longrightarrow\quad c=\frac{u^Tb}{u^Tu}.

The denominator is strictly positive because u≠0u\ne0. This perpendicularity gives the closest point. For any other coefficient c+dc+d, the error is (b−cu)−du(b-cu)-du. The two pieces are perpendicular, so the squared norm is ∥b−cu∥2+d2∥u∥2\|b-cu\|^2+d^2\|u\|^2, no smaller than the projected error. The argument is the Pythagorean theorem, not merely a derivative calculation.

For b=(3,1)b=(3,1) and u=(1,1)u=(1,1), c=4/2=2c=4/2=2, the projection is (2,2)(2,2), and the residual is (1,−1)(1,-1). Their dot product is zero. If the columns of QQ form an orthonormal basis for a subspace, the projection is QQTbQQ^Tb. Each coefficient comes from one dot product. The residual is perpendicular to every basis vector and therefore to the whole subspace.

Exact Euclidean coordinates: pTr=0p^Tr=0. The residual is not a vertical error to the diagonal line.

D. Least squares is projection onto the column space#

For p=Axp=Ax to be the projection of bb, its residual must satisfy AT(b−Ax)=0A^T(b-Ax)=0. Thus the normal equations are

ATAx=ATb.A^TAx=A^Tb.

When AA has independent columns, ATAA^TA is invertible: for nonzero zz, zTATAz=∥Az∥2>0z^TA^TAz=\|Az\|^2>0. If columns are dependent, minimizers need not be unique, although the projected vector AxAx is unique. Explicitly forming the inverse is not the preferred numerical algorithm. A QR factorization A=QRA=QR, with orthonormal columns in QQ and upper triangular RR, reduces the problem to Rx=QTbRx=Q^Tb. The lab uses modified Gram–Schmidt to illustrate this geometry. More robust libraries use methods such as Householder QR or SVD; the small lab is not a replacement for them. [LA]

Fit a line y≈β0+β1ty\approx\beta_0+\beta_1t to (t,y)=(0,1),(1,2),(2,2)(t,y)=(0,1),(1,2),(2,2). Then

A=(101112),b=(122),ATA=(3335),ATb=(56).A=\begin{pmatrix}1&0\\1&1\\1&2\end{pmatrix},\quad b=\begin{pmatrix}1\\2\\2\end{pmatrix},\quad A^TA=\begin{pmatrix}3&3\\3&5\end{pmatrix},\quad A^Tb=\begin{pmatrix}5\\6\end{pmatrix}.

Subtract the first normal equation from the second to get 2β1=12\beta_1=1, hence β1=1/2\beta_1=1/2 and β0=7/6\beta_0=7/6. Predictions are 7/6,5/3,13/67/6,5/3,13/6 and residuals −1/6,1/3,−1/6-1/6,1/3,-1/6. Their sum is zero, and their dot product with (0,1,2)(0,1,2) is zero. Those two checks verify perpendicularity to both design columns. The line minimizes squared vertical response residuals at fixed tt, not arbitrary geometric distances in the (t,y)(t,y) plane.

E. Eigenvectors identify directions preserved by a square map#

An eigenvector is a nonzero vector vv satisfying Av=λvAv=\lambda v. The scalar λ\lambda is its eigenvalue. The zero vector is excluded because it satisfies the equation for every λ\lambda and would identify no direction. Eigenvalues solve det⁡(A−λI)=0\det(A-\lambda I)=0, but deriving the characteristic polynomial by hand is not the default stable algorithm for a large matrix.

For A=(2112)A=\begin{pmatrix}2&1\\1&2\end{pmatrix}, vectors (1,1)(1,1) and (1,−1)(1,-1) have eigenvalues 3 and 1. Normalize them to form an orthogonal matrix QQ; then A=Qdiag⁡(3,1)QTA=Q\operatorname{diag}(3,1)Q^T. In those coordinates, repeated application simply multiplies the two components by powers of 3 and 1. This explains why one direction dominates long-term growth. Symmetric real matrices admit an orthonormal eigenbasis; a general matrix may not, may have complex eigenvalues, or may lack enough independent eigenvectors.

A real symmetric matrix is positive definite when xTAx>0x^TAx>0 for every nonzero real xx. Its eigenvalues are then positive, and a quadratic energy 12xTAx\frac12x^TAx curves upward in every direction. Positive diagonal entries alone do not establish this property. For a symmetric 2×22\times2 matrix, the first leading diagonal entry and determinant being positive are sufficient. In higher dimensions, use an appropriate criterion or factorization, not a guessed extension of a two-dimensional rule.

F. Singular values separate rotations from stretching#

For any real m×nm\times n matrix, an SVD has the form A=UΣVTA=U\Sigma V^T, with orthogonal square U,VU,V and rectangular nonnegative diagonal Σ\Sigma. Read this right to left: change input coordinates, stretch or erase principal directions, then change output coordinates. The nonzero singular values are square roots of the positive eigenvalues of ATAA^TA. They apply to rectangular maps and describe directional gains even when eigenvectors of AA itself are not appropriate.

For A=(1100)A=\begin{pmatrix}1&1\\0&0\end{pmatrix}, the input direction (1,1)/2(1,1)/\sqrt2 is stretched by 2\sqrt2 to output direction (1,0)(1,0), while (1,−1)/2(1,-1)/\sqrt2 is erased. The rank is one. Keeping the largest singular directions gives a low-rank approximation; the truncated SVD has an optimality theorem for specified matrix norms, but it does not automatically preserve the features that a human application considers important. Numerical rank also requires a tolerance relative to scale and measurement uncertainty.

G. Independent practice#

F foundation C standard course work T transfer S optional stretch L runnable lab or project. Attempt the complete set before opening its solutions.

A02.01FSolution

Project b=(4,1)b=(4,1) onto the line spanned by u=(2,1)u=(2,1). Compute the residual, verify orthogonality, and give the squared distance to the line.

A02.02CSolution

Reproduce the line-fit calculation above without looking at the solution. Verify both normal equations and compute the residual sum of squares. Explain why an exact fit is impossible.

A02.03CSolution

For A=(2112)A=\begin{pmatrix}2&1\\1&2\end{pmatrix}, derive both eigenvalues and a normalized eigenbasis. Use it to compute A3(1,0)TA^3(1,0)^T without three full matrix multiplications.

A02.04TSolution

Give a symmetric 2×22\times2 matrix with positive diagonal entries that is not positive definite, and exhibit a direction with negative quadratic form. For B=(1100)B=\begin{pmatrix}1&1\\0&0\end{pmatrix}, identify a null direction and both singular values.

A02.05LabSolution

Implement the full-column-rank least-squares interface in least_squares_lab.py using modified Gram–Schmidt QR and triangular back substitution. Reject incompatible shapes, nonfinite inputs, and a numerically dependent column according to the stated tolerance. Test the three-point line fit and verify AT(b−Ax)A^T(b-Ax) is near zero. Explain what the tolerance does not guarantee.

Optional small hints

A02.03: decompose (1,0)(1,0) as one half of (1,1)+(1,−1)(1,1)+(1,-1). A02.04: make the off-diagonal magnitude larger than the diagonal entries. A02.05: subtract the projection onto each previously computed orthonormal column.

H. Complete solutions: A02#

Compare the first step where your work differs. A corrected answer is not yet an independent success.

A02.01Show solution

The residual defines the error

uTb=2(4)+1(1)=9u^Tb=2(4)+1(1)=9 and uTu=5u^Tu=5, so p=(9/5)(2,1)=(18/5,9/5)p=(9/5)(2,1)=(18/5,9/5). The residual is r=(2/5,−4/5)r=(2/5,-4/5). Its dot product with uu is 4/5−4/5=04/5-4/5=0, and the squared distance is 4/25+16/25=4/54/25+16/25=4/5. By the perpendicular decomposition argument, every other point on the line has at least this squared distance. The residual is a vector; the squared distance is a nonnegative scalar.

Back to A02.01
A02.02Show solution

An overdetermined but solvable approximation

The normal equations yield β0=7/6\beta_0=7/6, β1=1/2\beta_1=1/2. Substitution gives 3(7/6)+3(1/2)=53(7/6)+3(1/2)=5 and 3(7/6)+5(1/2)=63(7/6)+5(1/2)=6. The residual sum of squares is 1/36+1/9+1/36=1/61/36+1/9+1/36=1/6. An exact fit through the first two points would have intercept 1 and slope 1, predicting 3 at t=2t=2, not 2. Least squares therefore solves an approximation problem, not the inconsistent original equalities.

Back to A02.02
A02.03Show solution

Use coordinates adapted to the map

det⁡(A−λI)=(2−λ)2−1=(λ−3)(λ−1)\det(A-\lambda I)=(2-\lambda)^2-1=(\lambda-3)(\lambda-1), so eigenvalues are 3 and 1. Corresponding normalized vectors are q1=(1,1)/2q_1=(1,1)/\sqrt2, q2=(1,−1)/2q_2=(1,-1)/\sqrt2. They are orthonormal. Since (1,0)=(q1+q2)/2(1,0)=(q_1+q_2)/\sqrt2, applying A3A^3 gives (27q1+q2)/2=(14,13)(27q_1+q_2)/\sqrt2=(14,13). Check directly once: A2=(5445)A^2=\begin{pmatrix}5&4\\4&5\end{pmatrix} and A3=(14131314)A^3=\begin{pmatrix}14&13\\13&14\end{pmatrix}. The eigenbasis predicts the same first column.

Back to A02.03
A02.04Show solution

Diagonal signs are not enough

Take A=(1221)A=\begin{pmatrix}1&2\\2&1\end{pmatrix} and x=(1,−1)Tx=(1,-1)^T. Then Ax=(−1,1)TAx=(-1,1)^T and xTAx=−2<0x^TAx=-2<0. For BB, the null direction is (1,−1)T(1,-1)^T. Since BTB=(1111)B^TB=\begin{pmatrix}1&1\\1&1\end{pmatrix} has eigenvalues 2 and 0, the singular values are 2\sqrt2 and 0. One input direction is retained and stretched, the other erased.

Back to A02.04
A02.05Show solution

Reference implementation and numerical limits

code/solutions/least_squares_lab.pyPython
"""A02.05: modified Gram-Schmidt QR for a small full-column-rank matrix."""
import math

def least_squares(a: list[list[float]], b: list[float],
                  tolerance: float = 1e-12) -> list[float]:
    m = len(a)
    n = len(a[0]) if m else 0
    if not n or m < n or len(b) != m or any(len(row) != n for row in a):
        raise ValueError("a must be rectangular, m >= n; b must have m entries")
    if tolerance <= 0 or not math.isfinite(tolerance):
        raise ValueError("positive finite tolerance required")
    if any(not math.isfinite(v) for row in a for v in row) or any(
            not math.isfinite(v) for v in b):
        raise ValueError("finite data required")
    q: list[list[float]] = []
    r = [[0.0] * n for _ in range(n)]
    for j in range(n):
        v = [row[j] for row in a]
        for i in range(j):
            r[i][j] = math.fsum(q[i][k] * v[k] for k in range(m))
            v = [v[k] - r[i][j] * q[i][k] for k in range(m)]
        r[j][j] = math.sqrt(math.fsum(x * x for x in v))
        if r[j][j] <= tolerance:
            raise ValueError("numerically dependent columns at chosen tolerance")
        q.append([x / r[j][j] for x in v])
    y = [math.fsum(col[k] * b[k] for k in range(m)) for col in q]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - math.fsum(r[i][j] * x[j]
                                 for j in range(i + 1, n))) / r[i][i]
    return x

if __name__ == "__main__":
    print(least_squares([[1., 0.], [1., 1.], [1., 2.]], [1., 2., 2.]))

After each projection subtraction, the current column has had its component along an earlier qiq_i removed. Normalizing the residual constructs the next basis vector and the corresponding entries of RR. Back substitution solves Rx=QTbRx=Q^Tb. Exact arithmetic would make the residual orthogonal to the entire column space; floating-point arithmetic makes this approximate. A small column norm triggers rejection because normalization would magnify error. The absolute tolerance is a deliberately simple classroom policy: rescaling the data can change its decision, and near-dependent columns may still be difficult. A production solver should use a scale-aware rank criterion and a robust factorization. The tests verify the known solution, residual orthogonality, shape rejection, and rank failure; they do not certify all ill-conditioned matrices.

Back to A02.05

I. Retention and readiness#

Retrieve rank–nullity and the geometric meaning of a matrix column. Advance when you can derive a projection from perpendicularity, explain what least squares minimizes, and distinguish eigenvalues from singular values. Continue with numerical linear algebra and larger QR/SVD experiments before treating this introduction as advanced competence.