Accelerating the pace of engineering and science

# for

Execute statements specified number of times

## Syntax

```for index = values
statements
end
```

## Description

example

for index = values, statements, end executes a group of statements in a loop for a specified number of times. values has one of the following forms:

• initVal:endVal — Increment the index variable from initVal to endVal by 1, and repeat execution of statements until index is greater than endVal.

• initVal:step:endVal — Increment index by the value step on each iteration, or decrements index when step is negative.

• valArray — Create a column vector, index, from subsequent columns of array valArray on each iteration. For example, on the first iteration, index = valArray(:,1). The loop executes a maximum of n times, where n is the number of columns of valArray, given by numel(valArray,1,:). The input valArray can be of any MATLAB® data type, including a string, cell array, or struct.

## Examples

expand all

### Assign Matrix Values

Create a Hilbert matrix of order 10.

```s = 10;
H = zeros(s);

for c = 1:s
for r = 1:s
H(r,c) = 1/(r+c-1);
end
end
```

### Decrement Values

Step by increments of -0.2, and display the values.

```for v = 1.0:-0.2:0.0
disp(v)
end
```
```     1

0.8000

0.6000

0.4000

0.2000

0

```

### Execute Statements for Specified Values

```for v = [1 5 8 17]
disp(v)
end
```
```     1

5

8

17

```

### Repeat Statements for Each Matrix Column

```for I = eye(4,3)
disp('Current unit vector:')
disp(I)
end
```
```Current unit vector:
1
0
0
0

Current unit vector:
0
1
0
0

Current unit vector:
0
0
1
0

```

expand all

### Tips

• To programmatically exit the loop, use a break statement. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement.

• Avoid assigning a value to the index variable within the loop statements. The for statement overrides any changes made to index within the loop.

• To iterate over the values of a single column vector, first transpose it to create a row vector.