MATLAB - The for Loop



A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax

The syntax of a for loop in MATLAB is −

for index = values
   <program statements>
            ...
end

values has one of the following forms −

Sr.No. Format & Description
1

initval:endval

increments the index variable from initval to endval by 1, and repeats execution of program statements until index is greater than endval.

2

initval:step:endval

increments index by the value step on each iteration, or decrements when step is negative.

3

valArray

creates 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 for 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.

Example 1

Create a script file and type the following code −

for a = 10:20 
   fprintf('value of a: %d\n', a);
end

When you run the file, it displays the following result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

Example 2

Create a script file and type the following code −

for a = 1.0: -0.1: 0.0
   disp(a)
end

When you run the file, it displays the following result −

1
0.90000
0.80000
0.70000
0.60000
0.50000
0.40000
0.30000
0.20000
0.10000
0

Example 3

Create a script file and type the following code −

for a = [24,18,17,23,28]
   disp(a)
end

When you run the file, it displays the following result −

24

18

17

23

28
matlab_loops.htm
Advertisements