Array index became negative or illogical.

2 views (last 30 days)
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?

Accepted Answer

Hunter
Hunter on 6 Oct 2024
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))

More Answers (0)

Products


Release

R2024a

Community Treasure Hunt

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

Start Hunting!