How to find the projection matrix onto a subspace

Projecting onto a subspace finds the point in that subspace closest to the vector we start with. We can build one matrix that performs the projection for every input. Let’s form it from a basis for a plane in three dimensions.

Put the basis vectors into a matrix

Use the plane spanned by u=(1,-2,0) and v=(2,1,-2). Put these independent vectors into the columns of A.

A=[12-210-2]

The projection matrix is P=A(ATA)-1AT. The independent columns ensure that ATA is invertible.

Find the small matrix inside the formula

The basis vectors are perpendicular, so their mixed dot products are zero. The diagonal entries are their squared lengths.

ATA=[5009]
(ATA)-1=[150019]

Multiply to get the projection matrix

Multiplying the three factors gives the following matrix after multiplying every entry by 45.

45P=[29-8-20-841-10-20-1020]

Check an input and its perpendicular residual

For x=(1,0,0), the projection is Px=145(29,-8,-20). The remaining part is x-Px=145(16,8,20). Its dot products with the two basis vectors are zero, so the residual is perpendicular to the whole plane.