%% Polynomial Fit Examples
% Examples using data from textbook Example 4.2

format longg;

x=[3.35 3.40 3.50 3.60]'
f=[0.298507 0.294118 0.285714 0.277778]'
%f=1./x;
A=[ones(size(x)) x x.^2 x.^3]
b=A\f

display(['Function f(x)=1/x at x=3.44, f(x)=', num2str(1/3.44,'%1.16e')]);

display(['Cubic Interpolation at x=3.44, f(x)=', num2str(polyval(flipud(b),3.44),'%1.16e')]);

display(['Quadratic Interpolation at x=3.44, f(x)=', num2str(polyval(vander(x(1:3))\f(1:3),3.44),'%1.16e')]);

display(['Linear Interpolation at x=3.44, f(x)=', num2str(polyval(vander(x(2:3))\f(2:3),3.44),'%1.16e')]);

xx=3.44;

fp=-1/xx^2;
err=0;
display(['Function Derivative f''(x)=-1/x^2 at x=3.44,', char(10), ' f''(x)=', num2str(fp,'%1.16e'), ' error=', num2str(err,'%1.16e')]);

fcp=polyval(polyder(flipud(b)),xx);
err=abs(fcp-fp);
display(['Cubic Interpolation at x=3.44,', char(10), ' f''(x)=', num2str(fcp,'%1.16e'), ' error=', num2str(err,'%1.16e')]);

fqp=polyval(polyder(vander(x(1:3))\f(1:3)),xx);
err=abs(fqp-fp);
display(['Quadratic Interpolation at x=3.44,', char(10), ' f''(x)=', num2str(fqp,'%1.16e'), ' error=', num2str(err,'%1.16e')]);

fip=polyval(polyder(vander(x(2:3))\f(2:3)),xx);
err=abs(fip-fp);
display(['Linear Interpolation at x=3.44,', char(10), ' f''(x)=', num2str(fip,'%1.16e'), ' error=', num2str(err,'%1.16e'), char(10)]);


%Demonstrate Lagrange Polynomials
%a=x(1)
%b=x(2)
%c=x(3)

% %Ruin variable x... then let it =3.44, the point of interest
% x=3.44
% 
% P1=((x-b)/(a-b))*f(1)+((x-a)/(b-a))*f(2)
% P1p=f(1)/(a-b)+f(2)/(b-a)
% P1p=f(2)/(b-c)+f(3)/(c-b)
% 
% P2=((x-b)*(x-c)/((a-b)*(a-c)))*f(1)+((x-a)*(x-c)/((b-a)*(b-c)))*f(2)+((x-a)*(x-b)/((c-a)*(c-b)))*f(3)
% P2p=(2*x-b-c)*f(1)/((a-b)*(a-c))+(2*x-a-c)*f(2)/((b-a)*(b-c))+(2*x-a-b)*f(3)/((c-a)*(c-b))