%% Lagrange Polynomials %% Introduction % % Below, we compute the Lagrange polynomials that interpolate 7 equally % spaced data points. % clear all; close all; %% Plotting the Lagrange polynomials % % Below is a sample code fragment we could use to plot the Lagrange % interpolating polynomials. % N = 6; % Degree of the polynomials xdata = linspace(0,1,N+1); x = linspace(0,1,100)'; E = eye(N+1); for j = 1:N+1, lx = lagrange(xdata,x,j); clf; plot(x,lx,'b','linewidth',2); hold on; % Plot the data that is interpolated by the Lagrange polynomial ydata = E(:,j); plot(xdata,ydata,'k.','markersize',30); str = sprintf('Lagrange Polynomial %d',j-1); title(str,'fontsize',18); xlabel('x','fontsize',16); plot([-1 1],[1 1],'k--'); plot([-1 1],[0 0],'k-'); axis([0,1,-2,2]); snapnow; end %% Using Lagrange polynomials % % One way to use Lagrange polynomials to construct a polynomial % interpolant is is to construct the sum % $$% p(x) = \sum_{j=0}^{N} \ell_j(x) y_j %$$ % where the points $(x_j,y_j)$ are the % points we want to interpolate. In Matlab, the following code will % create this sum for us. % % Code that illustrates how to use the Lagrange polynomials to interpolate % a given data set (xdata,ydata). close all; N = 6; % Polynomial degree xdata = linspace(0,1,N+1); ydata = rand(1,N+1); % Generate random data to interpolate xf = linspace(0,1,200); px = 0; for j = 1:(N+1), px = px + lagrange(xdata,xf,j)*ydata(j); end plot(xf,px,'r','linewidth',2); hold on; plot(xdata,ydata,'k.','markersize',30); %% % % This is a very inefficient way to construct the % Lagrange interpolant. A much better way is to use the % Barycentric Formula. % %% Exercises % %
% For the following, you will use at four different methods for % computing the Lagrange polynomials. For each of the exercises below, % you can generate data for a degree 5 polynomial. % Use the formula for the Lagrange polynomial % $$% \ell_j(x) = \frac{\prod_{i = 0, i \ne j}^{i = n} (x-x_i)} % {\prod_{i = 0, i \ne j}^{i = N} (x_j-x_i)}, j = 0,1,..., 5 %$$ %
%
1. Use the Vandermonde matrix systems and the columns of the identity % matrix to compute the coefficients for the polynomials % $\ell_j(x)$.
2. %
3. Use polyfit to construct the same % polynomials.
4. %
5. Write the function lagrange used above to % explicitly construct the Lagrange polynomials. You will want to use % the Matlab function prod for this problem.
6. %
7. Use the Matlab functions conv to explicitly % construct coefficients for the Lagrange polynomial. Compare them to the % coefficients you obtained using the other methods. %
%

In each case, verify that the 6 Lagrange polynomials that you % construct sum to % $$\sum_{i=0}^{N=5}\ell_i(x) = 1$$ %

• Use each of the methods described above to construct a polynomial that % interpolates the points % $$% (-2,4), (-1,3), (0,5), (1,5), (2,-7), (3,-2) %$$ % Plot the data points along with the interpolating polynomial.
• %