% CLASS11NOV  lagrange form of polynomial, for same problem as in
%             class9nov.m

% the data
x = [-1  0  3  5]';
y = [ 1  2 -1  4]';

xp = (-2:0.01:6)';                     % a fine grid of x-values at which to plot polynomials

figure(1)
l0 = (xp - x(2)) .* (xp - x(3)) .* (xp - x(4)) / ( (x(1) - x(2))*(x(1)-x(3))*(x(1)-x(4)) );
l1 = (xp - x(1)) .* (xp - x(3)) .* (xp - x(4)) / ( (x(2) - x(1))*(x(2)-x(3))*(x(2)-x(4)) );
l2 = (xp - x(1)) .* (xp - x(2)) .* (xp - x(4)) / ( (x(3) - x(1))*(x(3)-x(2))*(x(3)-x(4)) );
l3 = (xp - x(1)) .* (xp - x(2)) .* (xp - x(3)) / ( (x(4) - x(1))*(x(4)-x(2))*(x(4)-x(3)) );
yp = y(1) * l0 + y(2) * l1 + y(3) * l2 + y(4) * l3;
plot(x, y, 'o', xp, yp) 
xlabel x, ylabel y, title('the interpolating polynomial')

figure(2)
plot([x x], [zeros(size(x)) ones(size(x))], 'o', ...
     xp, [l0 l1 l2 l3]) 
xlabel x, ylabel y, title('Lagranges cardinal polynomials')
legend(['   '; '   '; 'l_0'; 'l_1'; 'l_2'; 'l_3'])
