Lagrange Polynomials

Topics in this lab


Below, we compute the Lagrange polynomials that interpolate 7 equally spaced data points.

clear all;
close all;

Back to the top

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);

  hold on;

  % Plot the data that is interpolated by the Lagrange polynomial
  ydata = E(:,j);


  str = sprintf('Lagrange Polynomial %d',j-1);

  plot([-1 1],[1 1],'k--');
  plot([-1 1],[0 0],'k-');


Back to the top

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);

hold on;

This is a very inefficient way to construct the Lagrange interpolant. A much better way is to use the Barycentric Formula.

Back to the top


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. Use polyfit to construct the same polynomials.
  3. Write the function lagrange used above to explicitly construct the Lagrange polynomials. You will want to use the Matlab function prod for this problem.
  4. 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.
  • Compare your answers with the solutions.

    Back to the top

    Download this code

    Download this code here.

    Back to the top

    Get the code

    Do you want to try the above code fragments on your own? Download the Matlab script that produces this page here. (lab_10.m)

    Powered by MathJax

    Published with MATLAB® 8.2