Array indices must be positive integers or logical values.
Show older comments
I am writing a lagrange interpolator function using Neville's method but keep getting this error (array indices must be positive integers or logical values) in regards to initializing the p(i,0) values which are just the y values at the various x's in the vector. i'm given a vector of values x and a function y as well as a vector of points w to approximate.
function p = lagrangeval(x,y,w)
%% lagrangeval evalutates the Lagrange interpolant for a set of knots (x,y)
%% Inputs: numbers x1,x2,..xn; values f(x1),f(x2)..f(xn)
%% Output: p - the value of the polynomial going through the n data points
n=size(x,1);
k=size(w,1);
for i=1:n
p(i,0)=y(x(i));
end
for l=1:k
for i=1:n
for j=1:i
p(i,j)=(((w(l)-x(i-j+1))*p(i,j-1))-((w(l)-x(i+1))*p(i-1,j-1)))/(x(i+1)-x(i-j+1));
end
end
end
2 Comments
Thiago Henrique Gomes Lobato
on 3 Nov 2019
Matlab is one-based index, so you can't use "p(i,0)", but rather must use "p(i,1)" for the first array element. Every time the index of your array is zero you will have an error, so I would check this at first.
Amanda McGovern
on 4 Nov 2019
Answers (2)
Star Strider
on 3 Nov 2019
I suspect this is the problem:
p(i,0)=y(x(i));
Subscript references in MATLAB must start at 1. Note that positive integers are integers greater than zero. (Zero has no sign, so it can never be either positive or negative.)
Walter Roberson
on 4 Nov 2019
for j=1:i
p(i,j)=(((w(l)-x(i-j+1))*p(i,j-1))-((w(l)-x(i+1))*p(i-1,j-1)))/(x(i+1)-x(i-j+1));
j starts at 1, so j-1 starts at 0, which is a problem for p(i,j-1) . Also your i starts at i, so i-1 starts at 0, which is a problem for p(i-1,j-1)
Categories
Find more on Interpolation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!