# Lagrange polynomials

## Topics in this lab

## Introduction

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

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

Back to the top

## Lab exercises

- Use the Vandermonde matrix systems and the columns of the identity matrix to compute the coefficients for the polynomials $\ell_j(x)$.
- Use polyfit to construct the same polynomials.
- Write the function lagrange used above to explicitly construct the Lagrange polynomials. You will want to use the Matlab function prod for this problem.
- 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$$

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)

Published with MATLAB® 8.3