Solution for Ex 1. (At rst write the needed function).
1
function l = lagrange(i,x,xbar)2
% i−
th elementary Lagrange polynomial of3
% the points x evalued on xbar4
n = length(x); m = length(xbar);5
l = prod(repmat(xbar,1,n−
1)−
...6
repmat(x([1:i−
1,i+1:n]),m,1),2)...7
/prod(x(i)−
x([1:i−
1,i+1:n]));8
% Denominator of the product in Lagrange form:9
% prod(x(i)−
x([1:i−
1,i+1:n]))10
% Numerator of the product in Lagrange form:11
% repmat(xbar,1,n−
1)−
repmat(x([1:i−
1,i+1:n]),m,1)12
% repmat is needed to create an array for evaluating13
% the interpolant.14
% For undertanding the program write help repmat Then run the following script 1
clear all; close all;2
xbar = linspace(−
5,5,200)'; % evaluation points3
ybar = 1./(1+xbar.^2); % needed for plotting the fun4
for n=5:155
x=linspace(−
5,5,n); %equispaced interp. pts6
y=1./(1+x.^2); %Runge at the interp. pts7
for k=1:length(x)8
L(:,k)=lagrange(k,x,xbar);9
end10
p=L*y'; % compute the polynomial11
figure(1), plot(xbar,ybar,'g−−
', x,y,'bo',...12
xbar,p,'r−
');13
grid;14
legend('Original function',...15
'Interpolation points',...16
'Interpolation on equispaced points'), pause(.5)17
end1
-5 -4 -3 -2 -1 0 1 2 3 4 5 -1
0 1 2 3 4 5 6 7 8
Original function Interpolation points
Interpolation on equispaced points
2
Solution for Ex 2. On the script Esercizio2 write 1
x=[−
2 1 3];2
y=[−
2 11 17];3
P=polyfit(x,y,2)4
%P =5
%−
0.2667 4.0667 7.20006
% Since P is a row vector of length N+17
% containing the polynomial coefficients8
% in descending powers, in this example we have9
% P(1) = a_2; P(1) = a_1; P(3) = a_0.10
xx = linspace(−
2,3); % evaluation points11
Y = polyval(P,xx); % evaluate the interpolant12
plot(x,y,'or',xx,Y,'−
') % plot13
legend('Data',...14
'Interpolating polynomial')-2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5 3
-2 0 2 4 6 8 10 12 14 16 18
Data
Interpolating polynomial
3