How to limit the number of for Loops while executing while loops?

조회 수: 24 (최근 30일)
Wilson Weng
Wilson Weng 2017년 9월 14일
댓글: James Tursa 2017년 9월 15일
Hi wonderful MatLab community,
I have set up a for-loop with another for-loop within a while-loop so that it would run the function 'for i = 0 : Time_steps' for 3 times.
The coding I have so far:
for number_of_repeats = 1 : 3 %to repeat it 3 times
while number_of_repeats <= 3
for i = 0 : Time_steps %during each of the 3 times
statement to perform stuff for i= 0: Time Steps
end
end
end
However when when I run this code, the program runs non-stop and has a continuous cycle where n = 1,2,3,1,2,3...etc. How can I make it run only 3 times?
Thank you so much guys!

채택된 답변

James Tursa
James Tursa 2017년 9월 14일
In your while loop:
while number_of_repeats <= 3
The condition "number_of_repeats <= 3" is always true because the for-loop that it is contained in defines number_of_repeats as 1 to begin with. Hence the infinite loop.
If you only want the whole thing to run 3 times, then just get rid of the while loop entirely. E.g.,
for number_of_repeats = 1 : 3 %to repeat it 3 times
for i = 0 : Time_steps %during each of the 3 times
statement to perform stuff for i= 0: Time Steps
end
end
  댓글 수: 2
Wilson Weng
Wilson Weng 2017년 9월 15일
Hi James,
Thank you for the reply. However when I run the code without the while-loop for some reason the software would still slightly go over after the 3rd run by a few seconds (time steps). Is it possible to write the coding such that
'for i = 0: Time_steps' where on the third repeat to have a shorter time step?
e.g. on the third repeat only
i = 0 : Time_steps-50 %(seconds)
Thanks once again :)
James Tursa
James Tursa 2017년 9월 15일
Several ways one might do that. Here is a straightforward way that is easy to read and understand:
for number_of_repeats = 1 : 3 %to repeat it 3 times
if( number_of_repeats == 3 )
tdelta = 50;
else
tdelta = 0;
end
for i = 0 : Time_steps-tdelta %during each of the 3 times
statement to perform stuff for i= 0: Time Steps
end
end

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by