function P3(d)
% Fits a polynomial of degree d to the function exp(-x/2)sin(3x)
% at the points defined by linspace(0,10,200). The best fit polynomial
% is displayed and the minimum residuals for degree j=1:d is reported.
close all
% Set up the LS problem...
m = 200; 
x = linspace(0,10,m)';
A = ones(m,1);
for j=2:d+1
    A = [A x.*A(:,j-1)];
end
b = exp(-x/2).*sin(3*x);
% Solve for the coefficients of the best-fit polynomial of degree d...
[Q,R] = qr(A);
c = Q'*b;
alfa = R(1:d+1,1:d+1)\c(1:d+1);
% Display the pitting polynomial and exp(-x/2)sin(3x)...
y = A(:,1:d+1)*alfa;
plot(x,y,'r',x,b,'k',[0 10],[0 0],':k')
legend('poly fit','exp(-x/2)sin(3x)')
title(sprintf('Degree of fitting polynomial = %1d',d))
% Compute Error(p^(j)) where p^(j) is the best fit poly of degree j,j=1:d
res = zeros(d,1);
for j=1:d
    res(j) = sqrt(1/m)*norm(c(j+2:m))
end
figure 
plot(res)
ylabel('Norm of Minimum Residual')
xlabel('Degree of fitting polynomial')