function v = Nearest1(A,b)
% A is m-by-n and assume rank(A) = n < m.
% v is the vector in the orthogonal complement of Ran(A) that is nearest
% to b in the 2-norm

[m,n] = size(A);

% Method 1. (2 points)
[Q,R] = qr(A);
Q2 = Q(:,n+1:m);
% We must solve min norm(Q2*x - b)
x = Q2\b;
v = Q2*x;

% Method 2. (3 points)
% Realize via normal equations that x = Q2'*b = Q2*Q2'*b
[Q,R] = qr(A);
Q2 = Q(:,n+1:m);
% We must solve min norm(Q2*x - b)
x = Q2'*b;
v = Q2*x;

% Method 3. (5 points)
% Realize from I = QQ' = [Q1 Q2][Q1 Q2]' = Q1Q1' + Q2Q2'
% that Q2'*Q2' = I - Q1*Q1'
[Q1,R1] = qr(A,0);
v = b - Q1*(Q1'*b);

% Method 4. (4 points)
% Work with the "triangle-picture", i.e., drop a perpendicular
% from b to the plane of the blackboard to get A*xLS. The
% "perpendicular" b - A*xls is what you want.
% b - A*xLS = b - (Q1*R1)*(inv(R1)*Q1'*b) = b - Q1*Q1'*b
v = b - A*(A\b); % -1 for not using QR

% Note that Q2'*Q2 = eye(m-n,m-n), so from thye normal equation system
% (Q2'*Q2)x = Q2'*b
% we see that x = Q2'*b. Thus
v = Q2*(Q2'*b);