Can I pass a variable to the outside of a for loop after each iteration?

I am running a forloop and the jump for the for loop, n, is dependent upon a value generated within each turn of the loop.
for i = 1:n:100 for example, where after each iteration of the loop, the n changes value and would the jump distance would need to be different each time. For example, if it runs as i = 1, n = 3 at the end of the calculations, and then i would need to jump to i = 4, not to i = 2.
Is there any way this is possible? That value of needs to change with each iteration of the forloop run otherwise the program will not work.

Answers (1)

Is there any way this is possible?
Sure. For example,
n=3; i=1;
while i<200
disp("i="+i+" n="+n)
i=i+n;
n=ceil(2*log(i+n));
end
i=1 n=3 i=4 n=4 i=8 n=5 i=13 n=6 i=19 n=7 i=26 n=7 i=33 n=8 i=41 n=8 i=49 n=9 i=58 n=9 i=67 n=9 i=76 n=9 i=85 n=10 i=95 n=10 i=105 n=10 i=115 n=10 i=125 n=10 i=135 n=10 i=145 n=11 i=156 n=11 i=167 n=11 i=178 n=11 i=189 n=11

1 Comment

Note that this is a while loop, which is what I would use in this kind of situation.
If you are trying to use "for i" then do something like
nexti = 1;
for i=1:whatever
if i < nexti; continue; end
stuff
n = something appropriate
more stuff
nexti = i+n;
end

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Release

R2018a

Asked:

on 11 May 2022

Commented:

on 11 May 2022

Community Treasure Hunt

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

Start Hunting!