What does it mean when you put Loop = 1; in a program

10 visualizaciones (últimos 30 días)
Reila01
Reila01 el 15 de Abr. de 2020
Comentada: Walter Roberson el 15 de Abr. de 2020
this is just a random question but i noticed on a while loop program i was reading written by someone else that they defined
loop = 1
then when they began the while loop they started it off as while (loop). what does this do to a while loop? i usually see some condition being evaluated for while before a condition statement is presented but here im not familiar with why the while loop was used this way. this is an example of what im looking at:
loop = 1;
%initialize loop
while(loop)
statement
statement

Respuesta aceptada

David Hill
David Hill el 15 de Abr. de 2020
while 1%continuous loop until broken from within
if
break;
end
end

Más respuestas (1)

James Tursa
James Tursa el 15 de Abr. de 2020
This is a "forever" loop. It executes until a break statement is encountered. E.g., the general construct is
while( 1 )
% stuff
if( some condition is met )
break;
end
end
  2 comentarios
Reila01
Reila01 el 15 de Abr. de 2020
okay that makes sense thank you!
Walter Roberson
Walter Roberson el 15 de Abr. de 2020
However, it is possible that the code changes the variable named loop in order to break out of the loop.
The general form is
while condition
some code
if some condition
break
end
some more code
end
where the "if" and "some more code" might not be present.
A condition in MATLAB is anything that can be evaluated to be 0 or non-zero (and non-nan). That does not have to be a relational expression: it can be a simple variable:
need_a_valid_answer = true;
while need_a_valid_answer
how_much = input('How much to withdraw?');
if isnumeric(howmuch) && isscalar(howmuch) && howmuch >= 0
need_a_valid_answer = false;
end
end
To which you would add the knowledge that any non-zero value can be used instead of true:
remaining_tries = 5;
while remaining_tries %implicitly this is remaining_tries ~= 0
how_much = input('How much to withdraw?');
if isnumeric(howmuch) && isscalar(howmuch) && howmuch >= 0
remaining_tries = 0;
else
remaining_tries = remaining_tries - 1;
end
end

Iniciar sesión para comentar.

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by