
%% Homework 0: Interpolation examples  --  R. J. LeVeque
% This is a demonstration of using Matlab publish to combine code with
% descriptions.

%% Sample problem

% <latex>
% Determine the quadratic polynomial $p(x)$ that interpolates the data
% \[
% (-1,3),~~(0,-1),~~(1,2)
% \]
% first using the Vandermonde matrix and then using the Lagrange form of
% interpolating polynomial.
% </latex>

%% Interpolation data:

xj = [-1.; 0.; 1.]
yj = [3.; -1.; 2.]

%% Using monomials
% For a quadratic interpolation we use basis functions $1,~x,$ and $x^2$.


%%
% Define Vandermonde matrix:  The columns are the basis functions evaluated
% at the interpolation points.

A = [xj.^0, xj, xj.^2]

%% 
% Solve the system for the monomial coefficients:

c = A\yj

%% 
% plot the resulting polynomial on a fine grid:

x = linspace(-1, 1, 1001);
p = c(1) + c(2)*x + c(3)*x.^2;
plot(x,p)
hold on 
plot(xj,yj,'.','markersize',20)

%% Lagrange form
% <latex>
% Evaluate the Lagrange basis functions on the fine grid for plotting:
% Recall that the Lagrange polynomials are:
% \[
% L_1(x) = \frac{(x-x_2)(x-x_3)}{(x_1-x_2)(x_1-x_3)}, ~~
% L_2(x) = \frac{(x-x_1)(x-x_3)}{(x_2-x_1)(x_2-x_3)}, ~~
% L_3(x) = \frac{(x-x_1)(x-x_2)}{(x_3-x_1)(x_3-x_2)},
% \]
% </latex>

L1 = (x-xj(2)).*(x-xj(3)) / ((xj(1)-xj(2))*(xj(1)-xj(3)));
L2 = (x-xj(1)).*(x-xj(3)) / ((xj(2)-xj(1))*(xj(2)-xj(3)));
L3 = (x-xj(1)).*(x-xj(2)) / ((xj(3)-xj(1))*(xj(3)-xj(2)));

%%
% In this form, the data values are the coefficients

p = yj(1)*L1 + yj(2)*L2 + yj(3)*L3;

%%
% Plot the solution
clf
plot(x,p)
hold on
plot(xj,yj,'.','markersize',20)

%% Chebfun examples
% <latex>
% Use Chebfun to plot the function
% \[
% f(x) = \left(\frac{1}{1 + 25x^2}\right)^{10}
% \]
% and the function
% \[
% g(x) = 5 \int_0^x f(s)\, ds.
% \]
% What degree polynomial approximation is used for each?
% </latex>

x = chebfun('x');
f = (1./(1+25*x.^2)).^10;
g = 5*cumsum(f);
clf
plot(f,'b')
hold on
plot(g,'r')
legend('f','g')

disp(sprintf('The degree of f is %i', length(f)-1))
disp(sprintf('The degree of g is %i', length(g)-1))

