Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(a) Write a MATLAB function, called Lagrange_poly that inputs a set of data poin

ID: 3111839 • Letter: #

Question

(a) Write a MATLAB function, called Lagrange_poly that inputs a set of data points (x, y) = (dat x, dat y), a set x of numbers at which to interpolate, and outputs the polynomial interpolant, y, evaluated at x using Lagrange polynomial interpolation. Your function header should look something like: function y = Lagrange_poly(x, dat x, dat y) (b) Use the code you developed in Part (a) to interpolate the functions i. f(x) = e^-x^2 ii. f(x) = 1/1 + x^2 using the data points dat x = -5: 1: 5. Interpolate at the points x = -5: 0.001: 5. Plot the results and comment on the error. (c) Repeat part (b), except using the data dat x = -5: 0.5: 5. Compare your answer for this problem to what you got in part (b).

Explanation / Answer

(a)

function y = Lagrange_poly(x, datx, daty)

if size(datx) ~= size(daty)
disp('Size of data points do not match.');
return;
end

y = [];

for m = 1:length(x)
temp = 0;
for i = 1:length(daty)
denom = 1;
numer = 1;
for j = 1:length(datx)
if datx(i) ~= datx(j)
denom = denom*(datx(i) - datx(j));
numer = numer*(x - datx(j));
end
end
temp = temp + ((numer/denom)*(daty(i)));
end
y = [y; temp];
end

end

(b)

(i)

function F = Func1(x)
F = zeros(length(x) , 1);
for i = 1:length(x)
F(i) = exp(-x(i)^2);
end
end

In command window -

A = Lagrange_poly(-5:0.001:5, -5:1:5, Func1(-5:1:5));

x = -5:0.001:5;

plot(x, A(x), 'o');

hold on;

plot(x, exp(-x^2), 'bo')

Compare error between the two plots.

(ii)

function F = Func2(x)
F = zeros(length(x) , 1);
for i = 1:length(x)
F(i) = 1/(1 + x(i)^2);
end
end

In command window -

A = Lagrange_poly(-5:0.001:5, -5:1:5, Func2(-5:1:5));

x = -5:0.001:5;

plot(x, A(x), 'o');

hold on;

plot(x, 1/(1 + x^2), 'bo')

Compare error between the two plots.

(c)

Do the same as above, with x = -5:0.5:5;