Index in position 2 exceeds array bounds error

1 view (last 30 days)
Jay
Jay on 1 May 2020
Answered: Guillaume on 1 May 2020
function my_function(x,it,dt)
global time;
global t;
if t == 1
output.Num_useful = 0;
output.Deno = 0;
end
....
% Start of time-simulation iterations
for k = 1:1:it
k;
if (time(t,1)/3600) < 24 % Check for the final time
t = t+1; % update global counter
time(t,1)= time(t-1,1) + dt; % update global time [s]
n1= time(t,1)/3600; % update time [h]
.
.
.
.
end
end
I am getting the following error
Index in position 2 exceeds array bounds.
Error in my_function (line 99)
if (time(t,1)/3600) < 24
How can I fix this?

Answers (1)

Guillaume
Guillaume on 1 May 2020
How can I fix this?
By ensuring that time has at least 1 column before calling your function. At the moment, it is empty since it doesn't even have one column.
Unfortunately, time and the poorly named t, are global and you've just fallen foul of one of the many problems with global variables. It's hard to keep track of their state since any piece of code can modify (or not modify when it should) the state of a global variable.
My recommendation would be to rewrite your code so it doesn't use global variables at all. Unfortunately, we don't have enough information about it give more advice.

Community Treasure Hunt

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

Start Hunting!