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
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
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);
count became 107 after iteration #11

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by