"Index exceeds the number of array elements (2)." error that always gives the index size observed as one less than the vector i am entering

4 views (last 30 days)
function p = cubicSplineCoefficients(x,y)
x = [1 2 3];
y = [5 6 7];
pp = spline(x,y)
n = length(x);
d = diff(x);
A = 2*diag(d(1:n-1)) + diag(d(2:n),1) + diag(d(2:n),-1);
B = 3*(diff(y)./d-diff(y(1:n-1))./d);
u = A/B;
u = [0;u;0];
p.coef = zeros(n-1,4);
p.break = x;
for i = 1:n-1
p.coef(i,:) = [y(i) u(i) (3*(y(i+1)-y(i)) / d(i)-2*u(i)-u(i+1)) (2*(y(i)-y(i+1)) / d(i)+u(i)+u(i+1))];
end
end
The code is essentially doing the spline function without using the spline function from matlab (for a class assignment). I dont really understand why I am getting this error. If I change the input to x = [1 2] and y = [5 6], it would give the same error but end with (1). any help as to why this is happening would be great help, thanks.

Answers (1)

Walter Roberson
Walter Roberson on 9 Dec 2022
When you pass numeric values to diff then it is the difference operator, X(2:end)-X(1:end-1). The result always has one fewer entries in the dimension of the difference.
diff is only derivative if the input is symbolic or symfun.
If you need numeric approximation to derivative then use gradient()
  1 Comment
Brandon
Brandon on 9 Dec 2022
after replacing diff() with gradient(), it is giving me an error that says "matrix dimensions must agree" on the same line. what should i do to make this work?

Sign in to comment.

Tags

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!