%% Interpolation vs fitting

% revision history:
% 11/19/24 Mark D. Shattuck <mds> interpolationVfitting.m

%% setup
x=(0:1/10:1)';               % measurement points
xx=(-.1:.01:1.1)';           % interpolation/fit points
b=pi*sin(15*x)+2*cos(pi*x);  % exact measurements
e=randn(size(x))/10;         % error or noise
y=b+e;                       % measurement with noise

%% plot raw data
disp('plot raw data');
plot(x,y,'o'); 
axis([-.2 1.2 -5 5]);
pause; 

%% linear interpolation
disp('add linear interpolation');
plot(x,y,'o-');
plot(x,y,'o',xx,interp1(x,y,xx,'linear')); % using interp1
pause; 

%% add spline interpolation
disp('add spline');
plot(x,y,'o-',xx,spline(x,y,xx));
plot(x,y,'o-',xx,interp1(x,y,xx,'spline')); % using interp1
pause; 

%% add exact
disp('add exact');
bb=pi*sin(15*xx)+2*cos(pi*xx);
plot(x,y,'o-',xx,spline(x,y,xx),xx,bb);
pause; 

%% add linear-least-squares fit
% assume we know the frequencies 15 and pi
% solve:
% u1*sin(15*x)+u2*cos(pi*x)=y
% [sin(15*x) cos(pi*x)]*[u1 u2]'=y
%           A          *   u    =y
%         (Nx2)        * (2x1)  =(Nx1)
% solution u=A\y
disp('add LSQ (assume known frequencies)');
u=[sin(15*x) cos(pi*x)]\y;
plot(x,y,'o-',xx,spline(x,y,xx),xx,bb,...
     xx,[sin(15*xx) cos(pi*(xx))]*u);
disp('    fit       exact     %err');
disp([u [pi;2] (1-u./[pi;2])*100]);
pause; 

%% add nonlinear-least-squares fit
% fit to f(u,x)=u1*sin(u3*x)+u2*cos(u4*x)
disp('add non-LSQ (find frequencies)');
f=@(u,x) u(1)*sin(u(3)*x)+u(2)*cos(u(4)*x);  % fit function 
chi=@(u) sum(abs(f(u,x)-y));                 % chi^2 
U=fminsearch(chi,[3 1 14 3]');
plot(x,y,'o-',xx,spline(x,y,xx),xx,bb,...
     xx,[sin(15*xx) cos(pi*(xx))]*u,...
     xx,f(U,xx));
disp('    fit       exact     %err');
disp([U [pi;2;15;pi] (1-U./[pi;2;15;pi])*100])


