while loop to repeat when condition
while evaluates an expression,
and repeats the execution of a group of statements in a loop while
the expression is true. An expression is true when its result is nonempty
and contains only nonzero elements (logical or real numeric). Otherwise,
the expression is false.
Repeat Statements Until Expression Is False
while loop to calculate
n = 10; f = n; while n > 1 n = n-1; f = f*n; end disp(['n! = ' num2str(f)])
n! = 3628800
Skip to Next Loop Iteration
Count the number of lines of code in the file
magic.m. Skip blank lines and comments using a
continue skips the remaining instructions in the
while loop and begins the next iteration.
fid = fopen('magic.m','r'); count = 0; while ~feof(fid) line = fgetl(fid); if isempty(line) || strncmp(line,'%',1) || ~ischar(line) continue end count = count + 1; end count
count = 34
Exit Loop Before Expression Is False
Sum a sequence of random numbers until the next random number is greater than an upper limit. Then, exit the loop using a
limit = 0.8; s = 0; while 1 tmp = rand; if tmp > limit break end s = s + tmp; end
An expression can include relational operators
==) and logical
operators (such as
~). Use the logical operators
create compound expressions. MATLAB® evaluates compound expressions
from left to right, adhering to operator precedence rules.
Within the conditional expression of a
as short-circuit operators. This behavior is the same as
short-circuit in conditional expressions and statements, it is good
practice to use
| within the expression.
x = 42; while exist('myfunction.m','file') && (myfunction(x) >= pi) disp('Expressions are true') break end
The first part of the expression evaluates to false. Therefore, MATLAB does not need to evaluate the second part of the expression, which would result in an undefined function error.
If you inadvertently create an infinite loop (that is, a loop that never ends on its own), stop execution of the loop by pressing Ctrl+C.
If the conditional expression evaluates to a matrix, MATLAB evaluates the statements only if all elements in the matrix are true (nonzero). To execute statements if any element is true, wrap the expression in the
When nesting a number of
whilestatement requires an
whileloop is similar to a
do...whileloop in other programming languages, such as C and C++. However,
whileevaluates the conditional expression at the beginning of the loop rather than the end.
do % Not valid MATLAB syntax statements while expression
To mimic the behavior of a
do...whileloop, set the initial condition of
trueand place the conditional expression inside the loop. For example, implement the
do...whileloop above by using a MATLAB
while true statements if ~expression break end end