Can I pass a variable to the outside of a for loop after each iteration?
Show older comments
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
1 Comment
Walter Roberson
on 11 May 2022
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
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!