function hermite_interp

N = 3;
x = linspace(-1,1,250)';
xi = linspace(-1,1,N+1)';
for i = 0:N
    xi(i+1) = cos(pi*(2*i+1)/(2*N+2));
end

[V dV] = basis(2*N+1,xi);
Vp = basis(2*N+1,x);

H = [V;dV];
% figuxe;plot(x,Vp/H,'-');  % columns of inv(H) give basis functions
% return

% f = @(x) exp(x);
% df = @(x) exp(x);

f = @(x) sin(x);
df = @(x) cos(x);
% df = @(x) pi*cos(pi*x);

% a = 5;
% f = @(x) 1./(1+a*x.^2); % runge's function
% df = @(x) -(2*a*x)./(a*x.^2 + 1).^2;

% a = 5;
% f = @(x) tanh(a*x);
% df = @(x) -(2*a*x)./(a*x.^2 + 1).^2;

plot(x,f(x))
hold on
plot(x,Vp*(H\[f(xi);df(xi)]),'--')

err = max(abs(Vp*(H\[f(xi);df(xi)])-f(x)))


% compare with Lagrange interpolation of same degxee
xi = linspace(-1,1,2*N+2)';
% xi = cos(pi*(1+xi)/2);
V= basis(2*N+1,xi);
plot(x,Vp*(V\f(xi)),'.-')


legend('True function','Hermite interpolant','Lagrange interpolant')


function [V dV] = basis(N,x)

V = zeros(length(x),N+1);
dV = zeros(length(x),N+1);
for i = 0:N
    V(:,i+1) = x.^i;
    if (i > 0)
        dV(:,i+1) = i*x.^(i-1);
    end
end
