MATLAB Answers

Index in position 2 exceeds array bounds error

조회 수: 3(최근 30일)
Jay
Jay 1 May 2020
답변: Guillaume 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?

  댓글 수: 0

댓글을 달려면 로그인하십시오.

답변(1개)

Guillaume
Guillaume 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.

  댓글 수: 0

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by