Documentation Center

  • Trial Software
  • Product Updates

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.

    Note:   Within the condition expression of an if or while statement, logical operators & and | behave as short-circuit operators. This behavior is the same as && and ||, respectively. Since && and || consistently short-circuit in if and while condition expressions and statements, it is good practice to use && and || instead of & and | within expression.

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

More About

expand all

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.

  • 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.

See Also

| | | | | | |

Was this topic helpful?