How to find vector in the subspace 𝑊 that is the closest to y in mathematica

New to mathematica and have looked into the matrix page but can't find anything to help.

y= (4,3,3,1), u1=(1,1,0,1), u2= (-1,3,1,-2), u3=(-1,0,1,1)

• Also W is the subspace spanned by u's Nov 27, 2022 at 14:16
• What comes to mind is Orthogonalize and Projection. There are resource functions to project onto a subspace but I have not used them and can not guarantee that they will work as you might intend. You can verify the source code of the notebook to see if it makes sense to you. These are the resource functions ProjectionMatrix and ProjectOnSubspace Nov 27, 2022 at 14:39

We can minimize the square of the distance of λ1*u1 + λ2*u2 + λ3*u3 and y.

u1 = {1, 1, 0, 1};
u2 = {-1, 3, 1, -2};
u3 = {-1, 0, 1, 1};
y = {4, 3, 3, 1};
sol=Minimize[(λ1*u1 + λ2*u2 + λ3*u3 - y) . (λ1*u1 + λ2*u2 + λ3*u3 - y), {λ1, λ2,λ3}]
proj = λ1*u1 + λ2*u2 + λ3*u3 /. sol[[2]]


W = {{1, 1, 0, 1}, {-1, 3, 1, -2}, {-1, 0, 1, 1}};
y = {4, 3, 3, 1};


Find the coefficients x that minimize the squared deviation:

x = LeastSquares[Transpose[W], y]
(*    {8/3, 2/5, 0}    *)


From this, calculate the vector z that approximates y optimally in the least-squares sense:

z = Transpose[W] . x
(*    {34/15, 58/15, 2/5, 28/15}    *)


This is the same method as what cvgmt suggests but with an explicit call to the least-squares minimizer.