MATLAB: Lagrange Interpolation. Error: Subscript indices must either be real positive integers or logicals.

errornew user

I understand that this question has been addressed, however, newbie to software and struggling to apply solutions to my function. This is my code, I am unsure what needs to be added or removed. Please can you explain explicitly why you would add remove and the cause of the problem for my understanding.
function [L] = lagrangePseudo(x,y,xstar)
n = length(x);
for i = 0:n+1
prod = y;
for j = 0:n+1
if i ~=j
prod = prod*(xstar-x(j))/(x(i)-x(j));
end
end
sum = 0;
L = sum+prod;
end
format long
end

Best Answer

Not even trying to understand your algorithm, there are glaring problems with your code:
sum = 0;
L = sum + prod;
This is basically, the same as L = 0 + prod, which is L = prod. This is not doing much.
Next,
for i = 0 : something
x(i)
As the error message tells you, indices must be positive integers. The first element of x has index 1.
Next, I strongly recommend you do not use prod and sum as variable names, since these are two extremely important built-in functions of matlab.
Next, format long only affects display of numbers. This has no place in a function, particularly one that does not display anything.
Related Question