%% Polynomial Differentiation Examples
% Examples using data from textbook Example 4.2 and 5.1 (although with
% extra point)

format longg;

%Analytical Expressions
dx=0.05;
x=2.5:dx:4.5;
f=1./x;
df=-1./x.^2;
n=length(x);

%Plot...
figure(1);
plot(x,f,x,df);
title('Analytical');
legend('f(x)','f''(x)');
xlabel('x'); ylabel('f(x) or f''(x)');

%Forward
for i=1:n-1
    dff(i)=(f(i+1)-f(i))/dx;
end;

%Backward
for i=2:n
    dfb(i)=(f(i)-f(i-1))/dx;
end;

%Centered
for i=2:n-1
    dfc(i)=(f(i+1)-f(i-1))/(2*dx);
end;

%Plot...
figure(2);
plot(x(1:end),df(1:end),'o',x(1:end-1),dff,x(1:end),dfb,x(1:end-1),dfc);
title('Analytical');
legend('f''(x)','Forward f''(x)','Backward f''(x)','Centered f''(x)');
xlabel('x'); ylabel('f''(x)');

%Spline
PS=spline(x,f);
%Spline Derivative
Dcoefs=[3*PS.coefs(:,1),2*PS.coefs(:,2),PS.coefs(:,3)];
PSD=mkpp(PS.breaks,Dcoefs);

%Plot...
figure(3);
xx=2.5:0.005:4.5;
plot(x,f,'o',xx,ppval(PS,xx),x,df,'o',xx,ppval(PSD,xx)); 
legend('f(x)','Spline','f''(x)','Spline Derivative');
xlabel('x');
ylabel('f(x)');
