% poly fitting
% rob nowak 1/24/04 - www.ece.wisc.edu/~nowak
clear all
close all

% generate and plot "true" function
t = (0:.001:1)';
f = exp(-5*(t-.3).^2)+.5*exp(-100*(t-.5).^2)+.5*exp(-100*(t-.75).^2);
figure(1)
plot(t,f,'b','linewidth',3)

% generate n training data & plot
n = 100;
sig = 0.1; % std of noise
x = .97*rand(n,1)+.01;
y = exp(-5*(x-.3).^2)+.5*exp(-100*(x-.5).^2)+.5*exp(-100*(x-.75).^2)+sig*randn(size(x));
figure(1)
clf
plot(t,f,'b','linewidth',3)
hold on
plot(x,y,'.')

% fit with polynomial of order k (poly degree up to k-1)
k=15;
for i=1:k
V(:,i) = x.^(i-1);
end
p = inv(V'*V)*V'*y;
for i=1:k
Vt(:,i) = t.^(i-1);
end
yh = Vt*p;
figure(1)
clf
plot(t,f,'linewidth',3)
hold on
plot(x,y,'*','markersize',8)
plot(t,yh,'m','linewidth',3)
legend('true function', 'training data','polyfit')