| Contents | Index |
while expression statements end
while expression, statements, end repeatedly executes one or more MATLAB program statements in a loop as long as an expression remains true.
An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false.
Expressions can include relational operators (such as < or ==) and logical operators (such as &&, ||, or ~). MATLAB evaluates compound expressions from left to right, adhering to operator precedence rules.
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.
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 a continue statement.
You can nest any number of while statements. Each while statement requires an end keyword.
Within an if or while expression, all logical operators, including | and &, short-circuit. That is, if the first part of the expression determines a true or false result, MATLAB does not evaluate the second part of the expression.
Find the first integer n for which factorial(n) is a 100-digit number:
n = 1;
nFactorial = 1;
while nFactorial < 1e100
n = n + 1;
nFactorial = nFactorial * n;
endCount the number of lines of code in the file magic.m, skipping all blank lines and comments:
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
fprintf('%d lines\n',count);
fclose(fid);Find the root of the polynomial x3 - 2x - 5 using interval bisection:
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if fx == 0
break
elseif sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
disp(x)Take advantage of short-circuiting to avoid error or warning messages:
x = 42;
while exist('myfunction.m') && (myfunction(x) >= pi)
disp('Condition is true')
break
endbreak | continue | end | for | if | return | switch

Explore how to use MATLAB to make advancements in engineering and science.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |