Solution for Ex 1. At rst write the following function.
1
function [yt,b]=NewtonInterp(x,y,xt)2
% Newton form of the interpolating polynomial3
n=length(x); b=y;4
for i=2:n5
for j=2:i6
add=eps*((x(i)−
x(j−
1))<1.e−
5);7
b(i)=(b(i)−
b(j−
1))/(x(i)−
x(j−
1)+add);8
end9
end10
% part2: Horner scheme for evaluating the polynomial11
for i=1:length(xt)12
yt(i)=b(n);13
for k=n−
1:−
1:114
yt(i)=yt(i)*(xt(i)−
x(k))+b(k);15
end16
end Then, on the script Esercizio1:
1
clear all2
close all3
clc4
f=@(x) x+exp(x)+20./(1+x.^2)−
5; n=12;5
x=linspace(−
2,2,n); % interpolation nodes6
y=f(x); xt=linspace(−
2,2); % function values7
p=NewtonInterp(x,y,xt);8
err1=max(abs((p−
f(xt))))9
figure(), plot(x,y,'or',xt,p,'−−
r',xt,f(xt),'k');10
legend('Equispaced points','Newt. interp.',...11
'Original function');1
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2 -5
0 5 10 15 20
Equispaced points Newt. interp.
Original function
2
Solution for Ex 2. On the script named Esercizio2 write 1
clear all2
close all3
a=0; b=1;4
h =0.05; x=a:h:b; % equispaced points5
y=0.1+x+(10^(−
1))*rand(size(x)); % the data6
xx=linspace(a,b); % for the evaluation7
P=polyfit(x,y,1); % construct the approximant8
Y = polyval(P,xx); % evaluate the approximant9
plot(x,y,'or',xx,Y,'−
') % plot10
legend('Data',...11
'Approximating polynomial')0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
0 0.2 0.4 0.6 0.8 1 1.2
Data
Approximating polynomial
3
Solution for Ex 3. Modify the given script as follows.
1
clear all2
close all3
a=0; b=2*pi;4
h=0.01; x=a:h:b; % nodes5
y=cos(2*x)+(10^(−
1))*rand(size(x)); % perturbed data6
kk = 0;7
while kk <= 148
n = kk;9
% computes the coefficients10
coeff=polyfit(x,y,n);11
% evaluate the coefficients12
z=polyval(coeff,x);13
% computes the residual14
err2=norm(z−
y,2);15
fprintf('\n \t n: %2.0f norma2: %1.2e',n,err2);16
% plot the results17
ht=1/10000; u=a:ht:b;18
v=polyval(coeff,u);19
plot(x,y,'r.'); hold on;20
plot(u,v,'k−
','LineWidth',2);21
titlestr=strcat('Minimi quadrati di grado:',...22
num2str(n));23
title(titlestr);24
legend('Dati','Approssimante Minimi quadrati');25
hold off;26
pause(.2);27
kk = kk+1;28
end29
fprintf('\n \n');4