logo for matrixlab-examples.com
leftimage for matrixlab-examples.com

Iteration (for-loops)

The MATLAB iteration structure (for-loop) repeats a group of statements a fixed, predetermined number of times. A matching end closes the statements.

Repeating then means looping or cycling a process usually with the objective of approaching a desired goal or target.

Each repetition of the process is called an 'iteration', and the results of
one turn are used as the starting point for the next turn or cycle.

The general format is:

for variable = expression


c = 5;

% Preallocate matrix, fill it with zeros
a = zeros(c, c);

for m = 1 : c
    for n = 1 : c
        a(m, n) = 1/(m + n * 5);

The result is:

a =
    0.1667    0.0909    0.0625    0.0476    0.0385
    0.1429    0.0833    0.0588    0.0455    0.0370
    0.1250    0.0769    0.0556    0.0435    0.0357
    0.1111    0.0714    0.0526    0.0417    0.0345
    0.1000    0.0667    0.0500    0.0400    0.0333

The semicolon terminating the inner statement suppresses repeated printing,
and the a after the loop displays the final result.

It is a good idea to indent the loops for readability, especially when they are nested.

 From 'iteration' to home

 From 'iteration' to 'Matlab Code'

Nested  loops

While Statement

If Statement

Switch Statement

footer for matlab for loop page