while
while
loop to repeat when condition
is true
Syntax
whileexpression
statements
end
Description
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.expression
, statements
,
end
Examples
More About
Tips
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
any
function.To programmatically exit the loop, use a
break
statement. To skip the rest of the instructions in the loop and begin the next iteration, use acontinue
statement.When nesting a number of
while
statements, eachwhile
statement requires anend
keyword.The MATLAB
while
loop is similar to ado...while
loop in other programming languages, such as C and C++. However,while
evaluates 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...while
loop, set the initial condition ofwhile
totrue
and place the conditional expression inside the loop. For example, implement thedo...while
loop above by using a MATLABwhile
loop.while true statements if ~expression break end end
Extended Capabilities
Version History
Introduced before R2006a
See Also
return
| continue
| break
| for
| end
| if
| switch
| Short-Circuit
AND
| Short-Circuit
OR