How to find a projection matrix for a line

Projecting a vector onto a line keeps the part that points along the line. We can calculate that part using a dot product. Then we can write the whole operation as a matrix that works for every input vector.

Use a nonzero vector along the line

If u points along the line, the projection of v is v·uu·uu. The denominator divides by the squared length of u, so the formula also works when u is longer or shorter than a unit vector.

Project a vector onto the line through one, three

Let u=(1,3) and v=(0,2). The two dot products are v·u=6 and u·u=10.

610(1,3)=(35,95)
Project the vector zero, two onto the line through one, threeThe vector tip at zero, two drops perpendicularly to zero point six, one point eight on the line. The projection vector goes from the origin to that point.(0, 2)Line through (1, 3)(0.6, 1.8)0
The dashed segment is perpendicular to the line. The projection vector ends at the foot of that segment.

The projection is (0.6,1.8). The remaining part is v-(0.6,1.8)=(-0.6,0.2), whose dot product with (1,3) is 0.

Build a matrix that gives the same projection

For an input (x,y), the projection formula gives x+3y10(1,3). Its components are x+3y10 and 3x+9y10, so the projection matrix is

P=[110310310910]

Once a vector lies on the line, projecting it again leaves it in place. In matrix form, P2=P.