Array index became negative or illogical.

2 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Number Theory 的更多信息

产品


版本

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by