%% monomials

f = @(x) sin(10*x);
f = @(x) 1./(1 + 10*x.^2);

N = 33;
xN = linspace(-1,1,N+1)';
xN = cos(pi*(1+xN)/2);

% Vandermonde 
X = zeros(N+1);
for i = 0:N
    X(:,i+1) = xN.^i;
end
a = X\f(xN);

x = linspace(-1,1,10000);
p = 0;
for i = 0:N
    p = p + a(i+1)*x.^i;
end

plot(x,f(x),'-','linewidth',2)
hold on
plot(xN,f(xN),'o','linewidth',2)
plot(x,p,'--','linewidth',2)

grid on



%% lagrange form

N = 15;
xN = linspace(-1,1,N+1);
xN = cos(pi*(1+xN)/2);
x = linspace(-1,1,1000);

for j = 0:N % l_j(x)
    p = 1;
    for i = 0:N
        if (i~=j)
            p = p .* (x-xN(i+1))./(xN(j+1)-xN(i+1));
        end
    end
    plot(x,p)
    hold on
    plot(xN,1,'o')        
end

