% BRIEF RECAP of October 6th, 1998 NEEP271 lecture
% written by Fabian Waleffe 98/10/06
%
% We derived the two linear equations in two unknowns a,b
% to fit the data x(i), y(i)  to the straight line y=a x + b
% using the METHOD OF LEAST-SQUARES.
% 
% Discussed POLYNOMIAL FITS
%           FITS by HIGHEST ORDER POLYNOMIAL = POLYNOMIAL INTERPOLATION
% Briefly   LINEAR INTERPOLATION = PIECEWISE POLYNOMIAL OF DEGREE 1
%           SPLINE INTERPOLATION = PIECEWISE POLYNOMIAL OF DEGREE 3
%                                  with continuous 1st and 2nd derivatives.  
%           LINEAR CURVE FITS vs, NONLINEAR  CURVE FITS
%
%           y=y(t)= a sin(t)   + b cos(2 t) + c sin(3 t)        LINEAR!
%           y=y(t)= a sin(b t) + c cos(d t)                 NONLINEAR! (in b, d)
%
%           y=a exp(b t)     nonlinear but not really....
%           y=a t^b          nonlinear but not really....
%           

clear

x=[1:20]';     y=randn(length(x),1);  plot(x,y,'o')

p1=polyfit(x,y,1)   
p3=polyfit(x,y,3)

plot(x,y,'o',x,polyval(p1,x),x,polyval(p3,x))

p9=polyfit(x,y,9)

plot(x,y,'o',x,polyval(p1,x),x,polyval(p3,x),x,polyval(p9,x))
xlabel('x'), ylabel('y')

pause(2)

xf=[1:0.1:20]';  
hold on
plot(xf,polyval(p9,xf))
xlabel('x'), ylabel('y')
 hold off

disp(' ')
disp('TRY SPLINE')
disp(' ')

help spline
type spline

% Using polyfit for a simple power law fit 
% (which is an "impostor" nonlinear fit: it can be log-logged to
% a simple 1st order polyfit)

t=[1:100]';  y=4*t.^pi;
plot(t,y), pause(2)

figure(1), hold off, loglog(t,y,'-o'), xlabel('t'),ylabel('y')
figure(2), hold off, plot(log(t),log(y),'-o'),xlabel('log t'),ylabel('log y')

exponent = (log(y(10))-log(y(8))) / (log(x(10)) - log(x(8)))
