Effacer les filtres
Effacer les filtres

for loop inside while loop

9 vues (au cours des 30 derniers jours)
yehuda kristo
yehuda kristo le 11 Déc 2023
Commenté : Walter Roberson le 11 Déc 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 commentaire
Walter Roberson
Walter Roberson le 11 Déc 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 ?

Connectez-vous pour commenter.

Réponse acceptée

Walter Roberson
Walter Roberson le 11 Déc 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);
count became 107 after iteration #11

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by