MATLAB - The for Loop


Advertisements


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 −

Format Description
initval:endval increments the index variable from initval to endval by 1, and repeats execution of program statements until index is greater than endval.
initval:step:endval increments index by the value step on each iteration, or decrements when step is negative.
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
9/10
4/5
7/10
3/5
1/2
2/5
3/10
1/5
1/10
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