Array index became negative or illogical.

2 ビュー (過去 30 日間)
Hunter
Hunter 2024 年 10 月 6 日
回答済み: Hunter 2024 年 10 月 6 日
function [t,y] = impeuler(f,tspan,y0,N)
% Input:
% f = name of inline function or function M-file that evaluates the ODE
% (if not an inline function, use: euler(@f,tspan,y0,N))
% For a system, the f must be given as column vector.
% tspan = [t0, tf] where t0 = initial time value and tf = final time value
% y0 = initial value of the dependent variable. If solving a system,
% initial conditions must be given as a vector.
% N = number of steps used.
% Output:
% t = vector of time values where the solution was computed
% y = vector of computed solution values.
m = length(y0);
t0 = tspan(1);
tf = tspan(2);
h = (tf-t0)/N; % evaluate the time step size
t = linspace(t0,tf,N+1); % create the vector of t values
y = zeros(m,N+1); % allocate memory for the output y
y(:,1) = y0'; % set initial condition
for n=1:N
y(:,n+1) = y(:,n) + (h/2)*(f(t(n),y(:,n)) + f(t(n+h),y(:,n) + h*f(t(n),y(:,n)))); % implement Euler's method
end
t = t'; y = y'; % change t and y from row to column vectors
end
The code above is an improved euler's method that I was told to create. All variables above the for loop create the values they are supposed to, as I displayed all of them to the terminal and none had an error.
Though the for loop when processed returns the error,
Array indices must be positive integers or logical values.
Error in impeuler (line 29)
y(:,n+1) = y(:,n) + (h/2)*(f(t(n),y(:,n)) + f(t(n+h),y(:,n) + h*f(t(n),y(:,n)))); % implement Euler's method
I'm not seeing how any of the arrays managed to get any of their indices to zero or below. What is causing the array index to try and go negative or illogical?

採用された回答

Hunter
Hunter 2024 年 10 月 6 日
I figured out where the mistake was, in the improved eulers method, there is a part of the equation where it has f(t(n) + h, y(n)).
I ended up writting f(t(n + h), y(n)), which tried to make the array index 1.1, not a real array value.
It had to be changed to f(t(n + 1), y(n))

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeNumber Theory についてさらに検索

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by