%% Find the point on a plane which is closest to a given point

%% Find the point u on a plane which is closest to a given point b
% Define the plane as the span of the vectors [-1;2;1], [1;1;1]. Let b=[0;1;3].

v1 = sym([-1;2;1]); v2 = sym([1;1;1]); b = sym([0;1;3]);
A = [v1,v2];

M = A'*A      % matrix
g = A'*b      % and rhs vector for normal equations

c = M\g       % solve the normal equations
u = A*c

fillpoints([0;0;0],1.6*v1,1.6*(v1+v2),1.6*v2,'c'); hold on
arrow3(v1,'b','LineWidth',2); arrow3(v2,'b','LineWidth',2);
plotpoints(b,u,'ko:'); hold off
alpha(0.6); nice3d; label(b,'b',u,'u')
view(-80,20)

%% Check that the difference vector is really orthogonal on the plane.
r = u-b        % difference vector
dot(v1,r)      % check that r is orthogonal on v1
dot(v2,r)      % check that r is orthogonal on v2

