% Unit 4 (MATLAB Course @ UAM)
% (c) Alexander Knebe

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  polynomial interpolation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all, close all, clc

a=1.5;
b=8.7;
N=10;

x=linspace(a,b,N);
f=x.^2.*sin(x);

% plot function
plot(x,f,'o','MarkerSize',10)
xlabel('x')
ylabel('f(x)')


% calculate f(x) at mid-points using polynomial interpolation
% (p4interpol() finds the 2 left and 2 right points itself...)
xp = (x(2:N-2)+x(3:N-1))./2;  
fp = p4interpol(x,f,xp);
hold on
plot(xp,fp,'rx')

% calculate f(x) at mid-points using linear interpolation
% (we pass the left and right point to linterpol()...)
fp = zeros(1,length(xp));
for i=1:length(xp)
    
    % find left and right points
    ir = find(x>xp(i));
    ir = ir(1);
    il = ir-1;
    xl = x(il);
    fl = f(il);
    xr = x(ir);
    fr = f(ir);
    
    % linearly interpolate to xp(i)
    fp(i) = linterpol(xl,xr,fl,fr,xp(i));
end
plot(xp,fp,'gd')

legend('tabulated function','polynomial interpolation','linear interpolation','Location','NorthWest')
