Most systems \(A\mathbf x=\mathbf b\) have no exact solution — the data doesn't line up. Instead of giving up, we find the closest answer: project \(\mathbf b\) onto what \(A\) can reach, and solve there. This page builds the tools in order — orthogonal vectors, orthonormal bases, the projection matrix, and finally least squares.
Perpendicular means no shared direction: \(\mathbf a\cdot\mathbf b=0\).
Two vectors are orthogonal when their dot product vanishes. Drag the tips — the angle badge turns green the instant \(\mathbf a\cdot\mathbf b\) hits 0 (a right angle).
Perpendicular directions, each of length 1. The dream basis.
A set of vectors is orthonormal when they are mutually orthogonal and each has length 1 (\(\mathbf q_i\cdot\mathbf q_j=0\) for \(i\neq j\), \(\mathbf q_i\cdot\mathbf q_i=1\)). Stack them as columns of \(Q\) and something magic happens:
Why care? Projections and least squares below need \((A^{\mathsf T}A)^{-1}\). If the columns are orthonormal, \(A^{\mathsf T}A=I\) and the whole thing collapses to dot products. Gram–Schmidt is the recipe that turns any independent set into an orthonormal one — see the \(A=QR\) factorization.
Drop \(\mathbf b\) straight down onto the plane \(A\) can reach. The leftover is perpendicular to it.
Project \(\mathbf b\) onto a line through \(\mathbf a\): \(\mathbf p=\dfrac{\mathbf a^{\mathsf T}\mathbf b}{\mathbf a^{\mathsf T}\mathbf a}\,\mathbf a\). Onto a whole subspace (the column space of \(A\)) it becomes the projection matrix:
The error \(\mathbf e\) is orthogonal to the whole column space — that is exactly what "closest" means. Here \(A\) has two columns \(\mathbf a_1,\mathbf a_2\) spanning a plane in \(\mathbb R^3\). Move \(\mathbf b\) with the sliders: its shadow \(\mathbf p\) is the nearest point on the plane, and the red error \(\mathbf e\) always meets the plane at a right angle.
Fit a line to points that don't lie on any line. \(A\mathbf x=\mathbf b\) is unsolvable, so solve the projection instead.
Fit a straight line \(b=C+Dt\) to the data. Stack the points into \(A=\begin{bmatrix}1&t_1\\\vdots&\vdots\\1&t_m\end{bmatrix}\) and \(\mathbf x=\begin{bmatrix}C\\D\end{bmatrix}\). Unless the points are perfectly collinear, \(\mathbf b\) is not in the column space, so \(A\mathbf x=\mathbf b\) has no solution. Project instead: solve the normal equations, which are always solvable.
Drag the data points. The green best-fit line re-solves the normal equations live; the red bars are the residuals it makes as small as possible (in the squared sense).