Loop Statement

  • Loops are slow in MATLAB; whenever possible, replace them with array operations and built-in functions.

The loop statement—also called the loop control flow—is one of MATLAB’s four flow-control statements. It includes two loop constructs, for and while, and two control statements, continue and break.

for Loop

for i = <[start:<increment>:end]>
    block
end
  • i is initialized to start at the beginning of the loop

  • increment defaults to 1

    • When positive, each iteration checks whether i is end
    • When negative, each iteration checks whether i is end
  • As with Matlab Array - Creating, i iterates through the elements of an array.

In particular, for an arbitrary numeric array A you can write

for i = A
    block
end

where i is bound to each column vector of A; the loop runs once per column. For example, with A = rand(2,2,2) the code above produces (4 column vectors):

    0.5060
    0.6991
 
    0.8909
    0.9593
 
    0.5472
    0.1386
 
    0.1493
    0.2575

while Loop

while condExp
    block
end

The conditional expression condExp is evaluated exactly as in elseif.

continue Statement

continue exits the current iteration of the innermost loop and moves to the next iteration. Example:

for i = 1:3
    for j = 1:3
        if j == 2
            continue;
        end
        disp([i j])
    end
end

output:

1     1
 
1     3
 
2     1
 
2     3
 
3     1
 
3     3

break Statement

break exits the innermost loop entirely. Example:

for i = 1:3
    for j = 1:3
        if j == 2
            break;
        end
        disp([i j])
    end
end

output:

1     1
 
2     1
 
3     1