Written and maintained by CASRAI Editorial Board
Published
On this page
The while command in MATLAB repeats a block of statements for as long as a condition is true. This page is for researchers and analysts who need a loop whose number of passes is not known in advance, and it shows how to write one, how MATLAB decides the condition is true, how to leave it early with break, how to emulate a do-while loop, and why a loop never ends or never starts. Facts below come from the MathWorks documentation for while and break and the GNU Octave manual, all read on 2026-11-08.
What the while command is used for in research
Use while when you cannot say beforehand how many iterations you need: iterating until an estimate stops changing, reading until a condition on the data is met, or sampling until a value exceeds a threshold. When the count is known, a for loop is the usual choice; see Loops in MATLAB: for, while and how to stop them. For the branching statements you will often put inside a loop, see if in MATLAB and if-else in MATLAB.
Install or access (official source only)
while is part of the core MATLAB language and is documented on the official MathWorks reference page mathworks.com/help/matlab/ref/while.html. GNU Octave, a free alternative, documents its own version in The while Statement. For wider orientation to the environment, see MATLAB coding.
Step-by-step: write a while loop
The documented syntax is while expression, then the statements, then end. The statements repeat as long as the expression is true.
- Set up the variable the condition depends on before the loop starts.
- Write
whilefollowed by the condition on the same line. - Put the statements to repeat on the following lines, including one that changes the variable the condition tests.
- Close the loop with
end. Each nestedwhileneeds its ownend.
Worked example, the factorial of 10 (the MathWorks documentation uses the same task):
n = 10;
f = n;
while n > 1
n = n - 1;
f = f * n;
end
f
The condition is checked before each pass. After n reaches 1 the condition is false and the loop stops. The result is f = 3628800, which is 10 factorial.
How MATLAB decides the condition is true
According to the documentation, the expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). This one rule explains most surprises.
| Condition result | Does the body run? |
|---|---|
A nonzero scalar, or true |
Yes |
Zero, or false |
No |
| A matrix or vector with every element nonzero | Yes |
| A matrix or vector containing any zero element | No |
| An empty array | No (the result must be nonempty) |
Per the documentation, if you want the body to run when any element is nonzero, wrap the expression in any(...). For example, while any(x) keeps looping while at least one element of x is nonzero, whereas while x stops as soon as one element becomes zero.
For compound conditions the documentation recommends the short-circuit operators && and || over & and |, because the second part is then not evaluated when the first part already decides the result.
How to break out of a while loop in MATLAB
Use break. It ends the loop early and skips any later statements in it; control moves to the statement after the loop’s end. In nested loops, break exits only the loop it sits in, and the outer loop keeps running. Use continue instead when you only want to skip the rest of the current pass and start the next one.
s = 0;
while true
r = rand;
if r > 0.8
break
end
s = s + r;
end
This pattern, based on the MathWorks example that sums random numbers until one exceeds 0.8, loops until the break condition occurs. Because the number of passes depends on rand, the sum differs from run to run.
Do-while in MATLAB, with an example
A do-while loop runs its body once before testing the condition. MATLAB has no do...while statement. The documentation’s recipe is to use while true, put the statements first, then end the body with if ~expression followed by break:
k = 0;
while true
k = k + 1; % body runs at least once
disp(k)
if ~(k < 3)
break
end
end
This prints 1, 2, 3. Even if the exit test were already true at the start, the body would execute once, which a plain while would not do.
Output and how to read it
A while loop returns nothing by itself; what you see is the output of statements inside it. Statements without a trailing semicolon print on every pass, so a loop can flood the Command Window; add a semicolon to suppress printing and display the result after end, as in the factorial example. To confirm how many passes ran, increment a counter inside the loop and inspect it afterward.
Troubleshooting: why is my while loop infinite, or never run?
The loop never stops
- Press Ctrl+C to stop a running loop (documented by MathWorks).
- Check that something inside the loop changes the variable the condition tests. If nothing does, the condition stays true forever.
- Check the truth rule above: a condition that can never become false, such as a constant
1without abreak, runs indefinitely. - Editorial interpretation, not from the documentation: floating-point arithmetic can make an exact-equality test such as
x ~= 1never become false whenxgrows by 0.1 per pass, because repeated addition of 0.1 need not land exactly on 1. A comparison such asx < 1, or a tolerance, is safer.
The loop never runs
- If the condition is an array, one zero element makes it false. Wrap it in
any(...)if that is not what you want. - If the condition is empty (for example, comparing against an empty result), it is not true, so the body is skipped.
Nested loops
A break in an inner loop does not stop the outer one. To leave both, test a flag variable in the outer loop’s condition after the inner loop ends.
Free alternatives: GNU Octave
| Feature | MATLAB | GNU Octave |
|---|---|---|
| Loop keywords | while ... end |
while (condition) ... endwhile |
| When the condition is tested | Before each pass | Before each pass |
| Documentation | while | The while Statement |
The Octave page documents endwhile as the closing keyword; it does not describe a plain end there, so check Octave’s other pages before assuming it is interchangeable.
FAQ
How do I break out of a while loop in MATLAB?
Put break inside the loop, usually in an if block. It ends only the loop it is in and continues after that loop’s end.
Why is my while loop infinite?
The condition never becomes false: nothing updates the tested variable, the condition is a constant, or a floating-point comparison never matches exactly. Press Ctrl+C to stop it, then fix the condition or add a break.
How do I use while in JavaScript?
This page covers the MATLAB command only. JavaScript has its own while statement with different syntax; use JavaScript’s own documentation for it.
What is a do-while loop, with an example?
It is a loop that executes its body once before checking the condition. MATLAB lacks it, so use while true with an if ~expression, break at the end, as shown in the do-while section above.
What is the difference between while and for?
A for loop runs a set number of passes over a range or columns; a while loop runs until its condition is false. See Loops in MATLAB.







