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:

FormatDescription
initval:endvalincrements the index variable from initval to endval by 1, and repeats execution of program statements until index is greater than endval.
initval:step:endvalincrements index by the value step on each iteration, or decrements when step is negative.
valArraycreates 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.9000

    0.8000

    0.7000

    0.6000

    0.5000

    0.4000

    0.3000

    0.2000

    0.1000

     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


Advertisements
Advertisements