How to exit from loop function ?

Hi, I need to exit from a loop,should i use break ?
here is an example :
for j=1:10
if (condition 1)
a=5; % example
% continue step
elseif (condition 2)
a=2;
% continue
elseif (condition 3)
a=0;
% !!! reject step
break; % !!
end
What I do ?
Thanks.

6 comentarios

Jan
Jan el 1 de Mayo de 2021
The question is not clear yet. What does "rejecting a step" mean?
Yamina chbak
Yamina chbak el 1 de Mayo de 2021
thanks for answering, i want to exit from loop if my condition3
Jan
Jan el 1 de Mayo de 2021
Yes, and you do this already with the break command. So the code does already what you are asking for,
Yamina chbak
Yamina chbak el 1 de Mayo de 2021
Yes, it's working, i try it. Thanks @Jan.
Image Analyst
Image Analyst el 1 de Mayo de 2021
@A Achbak, then why have you not accepted @Jan's answer below yet? It will give him "reputation points" for helping you. I'll at least Vote for his answer so he'll at least get some from me.
Yamina chbak
Yamina chbak el 1 de Mayo de 2021
@Image Analyst Now I am accepted @Jan's answer. Sorry for being late : press Accepted answer.

Iniciar sesión para comentar.

 Respuesta aceptada

Jan
Jan el 1 de Mayo de 2021
Simply try it:
a = 0;
for j = 1:10
fprintf('j=%d a=%d\n', j, a);
if j < 3
a = 5;
elseif j < 6
a = 2;
elseif j == 8
a = 0;
fprintf('Breaking the loop...\n');
break;
end
fprintf(' >> next iteration\n');
end
fprintf('Loop finished. a=%d\n', a);

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Productos

Versión

R2018a

Preguntada:

el 1 de Mayo de 2021

Comentada:

el 1 de Mayo de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by