function ShowLSFit()
% Approximate the function f(x) = exp(-x/5)*cos(2x) across the interval
% [0,10] in the least squares sense.

% Let p(x) be the polynomial alfa(1) + alfa(2)x + ... + alfa(d+1)x^d
% where
d = 10;
% We choose alfa(1:d+1) so that
% phi(alfa) = ( p(x(1)) - f(x(1))^2 + ... + (p(x(m)) - f(x(m)))^2
% is minimized where
m = 100;
% and
x = linspace(0,10,m)';
% phi(alfa) = norm(A*alfa - b,2)^2 where
A = zeros(m,d+1);
A(:,1) = ones(m,1);
for k=1:d
A(:,k+1) = A(:,k).*x;
end
% and
b = exp(-x/5).*cos(2*x);
% Solve the least squares problem...
alfa = A\b;
D = diag(linspace(1,m/5,m)); alfa = (D*A)\(D*b);
% and display...
N = 1000;
z = linspace(0,10,N)';
figure
h(1) = plot(z,exp(-z/5).*cos(2*z),'k','linewidth',2);
zPower = ones(N,1);
F = alfa(1)*zPower;
for k=1:d
zPower = z.*zPower;
F = F + alfa(k+1)*zPower;
end
hold on
h(2) = plot(z,F,'r');
plot([0 10],[0 0],'m')
hold off
title(sprintf('degree = %1d m = %1d',d,m),'fontsize',16)
xlabel('f(x) = exp(-x/5)cos(2x)','fontsize',16)
legend(h,'f(x)','p(x)')
shg