Borrar filtros
Borrar filtros

restarting a while loop without finishing the remaining code.

28 visualizaciones (últimos 30 días)
I am trying to make a while loop that will restart the program when the criteria is met. Currently it will restart the program but only after the entire program has run and i want it to restart before finishing.

Respuesta aceptada

Marta Salas
Marta Salas el 8 de Mzo. de 2014
Editada: Marta Salas el 8 de Mzo. de 2014
continue command restart the while loop. When condition holds the code after the if will not be run.
while(1)
%%your code
if(condition)
continue;
end
%%your code
end
  6 comentarios
Marta Salas
Marta Salas el 8 de Mzo. de 2014
where is the attached code?
Justin
Justin el 8 de Mzo. de 2014
sorry i never actually clicked attach file

Iniciar sesión para comentar.

Más respuestas (1)

Marta Salas
Marta Salas el 9 de Mzo. de 2014
Editada: Marta Salas el 9 de Mzo. de 2014
Just in case you need the solution to your problem. You wanna break the while loop when all the values are not positive, so, you used 2 nested for:
for i=1:1:r
for j=1:1:c
if MS(i,j)<=0
fprintf('Please enter a new matrix with all positive values.\n')
z=1;
continue;
end
end
end
The "continue" statement passes control to the next iteration of the for loop or while loop in which it appears, skipping any remaining statements in the body of the loop. In this code you have nested for and while loops, it skips iteration on this for loop "for j=1:1:c".
For your problem, I would propose a solution like this one:
% look for values <=0 and [r,c] are the indexes where these values appear
% if there is no negative values, r and c are empty arrays
[r,c]= find(MS<=0);
if(~isempty(r) & ~isempty(c))
fprintf('Please enter a new matrix with all positive values.\n')
z=1;
continue;
end

Categorías

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

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by