Documentation

This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.

Loop Control Statements

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

  • for statements 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 = ones(1,10);
    for n = 2:6
        x(n) = 2 * x(n - 1);
    end
  • while statements loop as long as a condition remains true.

    For example, 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

Each loop requires the end keyword.

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 a break statement, or skip to the next iteration of a loop using a continue statement. For example, count the number of lines in the help for the magic function (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 pressing Ctrl+C.

See Also

| | | |

Was this topic helpful?