% CP7p5.m
% Interpolating N=6 data points using 
% monomial basis functions and cubic spline.
% Computer problem 7.5 on p. 337 of Heath
% Ming Leung, 10/02/05

clear all; hold off;
tV = [ 0.0 0.5 1.0 6.0 7.0 9.0 ]';
yV = [ 0.0 1.6 2.0 2.0 1.5 0.0 ]';

xPlot = 0:0.02:9;  % x points for plotting later

% Interpolation using monomials of degree N-1
n = length(tV); AS = ones(n,n);
for i=2:n, AS(:,i) = tV.*AS(:,i-1); end,
xV = AS\yV, 
% Evaluate the polynomial using Matlab's own 
% polynomial evaluation function polyval:
% Note ordering of coefficients of polynomial in Matlab:
%  Y = a(1)*X^N + a(2)*X^(N-1) + ... + a(N)*X + a(N+1)
yMonomial1 = polyval(xV(n:-1:1),xPlot);
% We can also use our own version of Horner's method:
yMonomial2 = Horner(xV,xPlot);
% The 2 result are the same as you can check:
diffMonomial = max(abs(yMonomial1-yMonomial2)),
plot(xPlot,yMonomial2,'b-','lineWidth',2);
axis([0 9 -0.3 2.5]); % uncomment this line to zoom in on the domain [0 2]
hold on;

xlabel('t','FontSize',18); ylabel('y','FontSize',18);
title('Interpolating 6 data points','FontSize',18);

% plot the points to be interpolated as red open circles
plot(tV,yV,'ro');

% Interpolation using the natural cubic spline
[xPlotCSpline, yPlotCSpline] = cubicSplineNaturalF(tV,yV,10);
% plot the resulting natural cubic spline in green
plot(xPlotCSpline,yPlotCSpline,'g','lineWidth',2);

% put legend to specify the different curves
legend('monomial basis','interpolation points','cubic spline',2);

% RESULTS:
%
% Both methods produces smooth curves that pass through 
% the given data points as required.
%
% The 2 methods give similar results at the beginning and end portions,
% but very different values near the middle
% where no data points are given.
%
% Natural cubic spline gives a more reasonable interpolant overall.
% Due to the high degree of the polynomial (5th degree), it oscillates
% too much within this domain to be a reasonable interpolant.