Skip to Main Content Skip to Search
Product Documentation

while - Repeatedly execute statements while condition is true

Syntax

while expression
   statements
end

Description

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.

Tips

Examples

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;
end
 

Count 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
end

See Also

break | continue | end | for | if | return | switch

Tutorials

  


Free MATLAB Interactive Kit

Explore how to use MATLAB to make advancements in engineering and science.


Download free kit

Trials Available

Try the latest version of MATLAB and other MathWorks products.


Get trial software
 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS