MATLAB: Index exceeds the number of array elements (1).

indexMATLAB

Errors from command window when calling function trapode
Error using fzero (line 306)
FZERO cannot continue because user-supplied function_handle ==> @(y)y(n)-y(n-1)-0.5*h*(f(t(n-1),y(n-1))+f(t(n),y(n))) failed with the error below.
Index exceeds the number of array elements (1).
Error in trapode (line 26)
Y = fzero(F,y(n-1));
I think the error is related to my function F has a single variable, y, but I'm creating it with y(n) and y(n-1). However, I don't know how to fix this one, and I couldn't get the other answers on this topic to work.
Thank you,
Rick
function [t,y] = trapode(f,a,b,alpha,N)
t = linspace(a,b,N+1);
y = zeros(size(t));
h = (b-a)/N;
y(1) = alpha;
for n = 2:N+1
F = @(y) y(n) - y(n-1) - 0.5*h*(f(t(n-1),y(n-1)) + f(t(n),y(n)));
Y = fzero(F,y(n-1));
y(n) = Y;
end
end

Best Answer

fzero only ever passes a scalar as its argument. The "y" that reaches inside F will be a scalar, and so cannot be accessed as y(n) or y(n-1)
You are basically creating a conflict between the variable named y that you are storing values into, and the trial value that is being passed into F. Maybe
F = @(ty) ty - y(n-1) - 0.5*h*(f(t(n-1),y(n-1)) + f(t(n),ty));
but I doubt it.
Related Question