for loop inside while loop
3 views (last 30 days)
Show older comments
yehuda kristo
on 11 Dec 2023
Commented: Walter Roberson
on 11 Dec 2023
I made for loop (with length n) to calculate something. After i look at the final result, i needed to rerun the for loop until condition A is reach (which could be done by while loop). How do i do that?
For example: I wanted to obtain count = 100 and already do this for loop. How do i add the while loop so that the for loop will rerun until count = 100? Is this possible? Or do i need to change the for loop into while loop? My code is much more complex than just counting even numbers, so i was looking a way if i can just add the while loop, not changing the whole loop using while.
a=randperm(100,20);
count = 0;
for i=1:length(a)
if mod(a(i),2) == 0 % searching for even numbers
count = count + 1;
end
end
1 Comment
Walter Roberson
on 11 Dec 2023
Do you want the for i loop to be exited as soon as the count of 100 is reached, or do you want the for i to conclude and only exit if 100 or more has been reached by the end of the iteration ?
Accepted Answer
Walter Roberson
on 11 Dec 2023
count = 0;
iters = 0;
while count < 100
iters = iters + 1;
a = randperm(100,20);
for i=1:length(a)
if mod(a(i),2) == 0 % searching for even numbers
count = count + 1;
end
end
end
fprintf('count became %d after iteration #%d\n', count, iters);
0 Comments
More Answers (0)
See Also
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!