for loop inside while loop
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
Walter Roberson
2023-12-11
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 ?
采纳的回答
Walter Roberson
2023-12-11
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!