lagrangian polynomial function giving the incorrect answer
Show older comments
I have to write a function that gives the lagrangian interpolating polynomial estimation for a point, given a set of points.
Here is what I wrote:
function polyatc = lagrange(Xlist, Ylist, c)
polyatc = 0;
xprod=1;
for i=1:size(Ylist)
for j= setdiff(1:size(Xlist), i)
xprod=xprod*((c-Xlist(j))/(Xlist(i)-Xlist(j)));
end
polyatc = polyatc+Ylist(i)*xprod;
end
disp(polyatc);
end
where polyatc should be the polynomial estimation for the function value at point x=c and xprod should be the section to the right of
in the interpolating polynomial: 
This all looks right to me and looks very similar to ones I have found online.
However, when I input: lagrange([1,5],[3,11],2) I get 3 when I should be getting 5 as the subsequent interpolating polynomial is 2x+1. I've tried following the logic of the code but I always come out with 5 and can't figure out where it is going wrong.
Accepted Answer
More Answers (1)
the cyclist
on 13 Aug 2019
I don't have a solution for you, but I can say that the line
xprod=xprod*((c-Xlist(j))/(Xlist(i)-Xlist(j)));
is never reached for your inputs.
I don't think you want
for i=1:size(Ylist)
because size(Ylist) is [1 2]. Maybe you meant
for i=1:length(Ylist)
?
Categories
Find more on Number Theory in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!