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

%%%%%%%%%%%%%%%%%%%%%%%%%%
%  linear 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)')


% generate a vector with positions where to calculate f(x) (i.e. mid-points for exercise)
xp = x(1:N-1)+diff(x)./2;  
fp = zeros(1,length(xp));



% A) we could use linterpol() like this which relies on the fact
%    that xp(i) lies in the middle of x(i) and x(i+1):
% fp = linterpol(x(1:N-1),x(2:N),f(1:N-1),f(2:N),xp);


% B) but this method is more flexible as it does not rely on the
%    fact that xp(i) lies in the middle of x(i) and x(i+1):
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 the interpolated values into the same figure
hold on
plot(xp,fp,'rx')

legend('tabulated function','interpolated values','Location','NorthWest')
