Index exceeds the number of array elements (1).

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

 Réponse acceptée

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.

3 commentaires

Rick Sellers
Rick Sellers le 27 Oct 2019
Thank you. That worked.
Rick Sellers
Rick Sellers le 27 Oct 2019
Made one change--the ty inside the function f I changed back to y(n). Still works, FYI.
Ummm, no. If changing that to y(n) "works" then you would have
ty - y(n-1) - 0.5*h*(f(t(n-1),y(n-1)) + f(t(n),y(n)))
and the - y(n-1) - 0.5*h*(f(t(n-1),y(n-1)) + f(t(n),y(n))) part would be constant in the input. When you fzero() input_variable minue constant then the only possible solution is that the input variable equals the constant. So if you believe that that code "works" then you should skip the fzero phase and simply have
Y = - y(n-1) - 0.5*h*(f(t(n-1),y(n-1)) + f(t(n),y(n)));

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Produits

Version

R2019b

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by