A good try at some code, with three errors in it. Well, essentially two errors, but you made one of those errors twice so I'm not sure where the error count really comes out. ;-)
Your first mistake is in this line:
Lets look at what happens.
The size of Ylist is NOT the number of elements in Ylist. It is a vector, of length 2. That is because Ylist is a 1x2 vector. Now what happens when you use 1:size(Ylist)?
It returns the number 1, so a bad idea, because that confuses the for loop. It goes only from 1 to 1, not 1 to the number of elements in Ylist as you want. Use numel instead. Use numel to learn how many elements are in an array of any size, although length will also tell you how many elements are in a vector. You actually made that mistake TWICE, in two for loops.
Next, you defined xprod as 1 BEFORE the outer loop. But the second time through the loop, it will use the last value from the previous iteration of the loop. Again, BAD. xprod needs to be initialized inside the main loop, so it will be properly initialized for the inner loop.
As a quick verification, what should the line be that passes through those points?
So, y = 2*x + 1, as you suggested it should be. (Sometimes I'm just too lazy to think.) So the prediction at x==2 should indeed be 5.
Here is my modified version of your code. As you can see, quite close, but with those spots fixed.
function polyatc = lagrange(Xlist, Ylist, c)
polyatc = 0;
for j= setdiff(1:numel(Xlist), i)
polyatc = polyatc+Ylist(i)*xprod;
When I run THAT code, I get, for c=2, I see this:
In fact, as a nice test, if I do this:
and then run my version of your code, I get this:
And that is what we should get. For any input c, the interpolant should produce 2*c+1.