Borrar filtros
Borrar filtros

for loop inside while loop

11 visualizaciones (últimos 30 días)
yehuda kristo
yehuda kristo el 11 de Dic. de 2023
Comentada: Walter Roberson el 11 de Dic. de 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 comentario
Walter Roberson
Walter Roberson el 11 de Dic. de 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 ?

Iniciar sesión para comentar.

Respuesta aceptada

Walter Roberson
Walter Roberson el 11 de Dic. de 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

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by