How to use a while loop with irregular step?

i would like to use a "while" loop ( while i<20) but with an irregular step. For example it goes this way : i=1,2,3, 5,7,9,12,15,18....it means it starts by a 1-step then by 2 then by a 3-step.

 채택된 답변

Walter Roberson
Walter Roberson 2015년 8월 8일

0 개 추천

while loops do not have steps. "for" loops can have steps but also can be irregular:
for i = [1,2,3, 5,7,9,12,15,18]

댓글 수: 5

bh dhouha
bh dhouha 2015년 8월 8일
So is it impossible to do the thing with while? i can not change the counter inside the loop ? ( like if i>3 i=i+2 )
If you do not change the value inside the loop then you have an infinite loop, so Yes, change it inside the loop in any way you prefer.
bh dhouha
bh dhouha 2015년 8월 8일
Just a final point :) if i'm going to use the for loop as u mentioned , and the sequence is too long [1 ,2 ,3,.....2000] how can i write this case : if i in [1,5] take 1-step. if i in [6,10] take a 2-step ....etc?
[1:1:5, 6:2:10, 11:3:20 ...]
bh dhouha
bh dhouha 2015년 8월 8일
thanks a lot

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

추가 답변 (1개)

David Young
David Young 2015년 8월 8일
편집: David Young 2015년 8월 8일

0 개 추천

You can do it with a for loop very simply:
for i = [1,2,3, 5,7,9, 12,15,18]
% < process using i >
end
By the way, some people take the view that it is unwise to use i or j as ordinary variables because of potential confusion with the imaginary unit, so it might be better to use ii or k or something.

댓글 수: 2

bh dhouha
bh dhouha 2015년 8월 8일
The loop that i mentioned is just a simple example.But what i have in reality is much complex and needs a "while" loop not a for loop. I know the "for" loop can be used with irregular increment but the problem is does that work with the "while" loop or no ? Thanks for the answer :)
bh dhouha
bh dhouha 2015년 8월 8일
By the way, if i'm going to use the for loop as u mentioned , and the sequence is too long [1 ,2 ,3,.....2000] how can i write this case : if i in [1,5] take 1-step. if i in [6,10] take a 2-step ....etc?

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2015년 8월 8일

댓글:

2015년 8월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by