Compute the projection p = (aT b / aT a) a and verify the residual is orthogonal. The idea in plain words, a worked example, and a check with the answers shown — part of the free Linear Algebra guides.
Projectingb onto the line througha means: stay on the line, get as close tob as possible.
The closest point is where the leftover is perpendicular to the line. Write the projection as a multiple of the direction,p=x^a. Requiringa⋅(b−x^a)=0 gives
x^=aTaaTb,p=x^a.
Takea=[12] andb=[43]. ThenaTb=4+6=10 andaTa=1+4=5, sox^=2 and
p=2[12]=[24].
Check:b−p=[2−1] anda⋅(b−p)=2−2=0 ✓
The perpendicularity condition is the whole idea
Why mustb−p be perpendicular toa? Because otherwise you could walk a little further along the line and reduce the distance.
Supposeb−p had a component alonga. Movingp slightly in that direction would shortenb−p — sop was not the closest point. The closest point is exactly the one where no direction along the line improves things, and the only way that can happen is for the error to have zero component alonga.
Formally, the distance squared fromb to a pointx^a on the line is
∥b−x^a∥2=∥b∥2−2x^(a⋅b)+x^2∥a∥2,
a quadratic inx^ opening upward. Its minimum is atx^=a⋅aa⋅b — the same formula, derived by calculus instead of by orthogonality. Two routes, one answer, which is a good sign that the answer is right.
Note what the formula refuses to do. It never divides byb, only byaTa. The direction matters and the target does not.
One projection with a negative coefficient
Problem. Projectb=[4−1] onto the line througha=[−12].
Solution.aTb=−4−2=−6 andaTa=1+4=5, so
x^=5−6,p=−56−12=6/5−12/5.
The check.b−p=[4−6/5−1+12/5]=[14/57/5], anda⋅(b−p)=−514+514=0 ✓
On the negative coefficient. A negativex^ means the closest point lies on the oppposite side of the origin froma — the line extends both ways, so this is perfectly normal. It is not a sign error. Ifx^ comes out zero you would be in the perpendicular case; any other value is legitimate.
By the end you can
Compute the projection p = (a^T b / a^T a) a and verify the residual is orthogonal
Explain why the closest point is the one with a perpendicular residual
Use the special cases b = a and b perpendicular to a as checks
Two questions
(a) Projectb=[50] onto the line througha=[11].
(b) A projectionp has∥p∥=3 and∥b∥=6. What is the angle betweenb and the line?