MATLAB Function Reference
for

Execute block of code specified number of times

Syntax

• ```for `variable` = ```expression
```    `statements`
end
```

Description

The general format is

• ```for ```variable = expression
```    ```statement
```    ...
```statement
```end
```

The columns of the `expression` are stored one at a time in the variable while the following statements, up to the `end`, are executed.

In practice, the `expression` is almost always of the form `scalar` `:` `scalar`, in which case its columns are simply scalars.

The scope of the `for` statement is always terminated with a matching `end`.

Examples

Assume `k` has already been assigned a value. Create the Hilbert matrix, using `zeros` to preallocate the matrix to conserve memory:

• ```a = zeros(k,k)  % Preallocate matrix
for m = 1:k
for n = 1:k
a(m,n) = 1/(m+n -1);
end
end
```

Step `s` with increments of -`0.1`

• ```for s = 1.0: -0.1: 0.0,..., end
```

Successively set `e` to the unit `n`-vectors:

• ```for e = eye(n),..., end
```

The line

• ```for V = A,..., end
```

has the same effect as

• ```for k = 1:n, V = A(:,k);..., end
```

except `k` is also set here.

`end`, `while`, `break`, `continue`, `return`, `if`, `switch`, `colon`