Documentation

Loop Control Statements

With loop control statements, you can repeatedly execute a block of code. There are two types of loops:

  • forstatements loop a specific number of times, and keep track of each iteration with an incrementing index variable.

    For example, preallocate a 10-element vector, and calculate five values:

    x = 1 (10);为n = 6 x (n) = 2 * (n - 1);end
  • whilestatements loop as long as a condition remains true.

    For example, find the first integernfor whichfactorial(n)is a 100-digit number:

    n = 1; nFactorial = 1; while nFactorial < 1e100 n = n + 1; nFactorial = nFactorial * n; end

Each loop requires theendkeyword.

It is a good idea to indent the loops for readability, especially when they are nested (that is, when one loop contains another loop):

A = zeros(5,100); for m = 1:5 for n = 1:100 A(m, n) = 1/(m + n - 1); end end

You can programmatically exit a loop using abreakstatement, or skip to the next iteration of a loop using acontinuestatement. For example, count the number of lines in the help for themagicfunction (that is, all comment lines until a blank line):

fid = fopen('magic.m','r'); count = 0; while ~feof(fid) line = fgetl(fid); if isempty(line) break elseif ~strncmp(line,'%',1) continue end count = count + 1; end fprintf('%d lines in MAGIC help\n',count); fclose(fid);

Tip

If you inadvertently create an infinite loop (a loop that never ends on its own), stop execution of the loop by pressingCtrl+C.

See Also

||||