MATLAB Answers

0

How to use a while loop with irregular step?

Asked by bh dhouha on 8 Aug 2015
Latest activity Commented on by bh dhouha on 8 Aug 2015
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.

  0 Comments

Sign in to comment.

Tags

2 Answers

Answer by Walter Roberson
on 8 Aug 2015
 Accepted Answer

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 Comments

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

Sign in to comment.


Answer by David Young
on 8 Aug 2015
Edited by David Young
on 8 Aug 2015

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 Comments

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 :)
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?

Sign in to comment.