English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MATLAB for loop

MATLAB Loop Statements

For loopIt is a repetitive control structure that allows you to write loops that need to be executed a specific number of times efficiently.

Syntax

The syntax of the for loop in MATLAB is:

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

Value(values) have one of the following forms-

NumberFormat and Description
1

initval:endval

The index variable is frominitvaltoendval increments1and repeat executionprogram statements,untilindexis greater thanendval.

2

initval:step:endval

In each iteration, theindexThe value is increased by the value of step, if step is negative, then theindexis decreased.

3

valArray

In each iteration, the value from the arrayof valArray'ssubsequent column creates a column vectorindex. For example, in the first iteration, index = valArray(:,1). The loop executes at most n times, where n isvalelof the columnnum, by numel(valArray,1, :) given. InputvalArrayCan be any MATLAB data type, including strings, cell arrays, or structures.

Instance1

Create a script file and enter the following code-

for a = 10:20 
   fprintf('value of a: %d\n', a);
end
When running 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

Instance2

Create a script file and enter the following code-

for a = 1.0: -0.1: 0.0
   disp(a)
end
When running 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

Instance3

Create a script file and enter the following code-

for a = [24,18,17,23,28]
   disp(a)
end
When running the file, it displays the following result-
24
18
17
23
28

MATLAB Loop Statements