Related Tags

matlab
communitycreator

# What are the types of loops in MATLAB?

Mahnoor Zaheer

### Overview

Loops are required to execute a piece of code multiple times. MATLAB allows two different types of loops to be executed, which are explained in this shot:

1. While loop
2. For loop

### While loop

The syntax of this loop is:

while (expression)
code
end
The syntax of while loop in MATLAB

The while loop executes as long as the expression remains True. As the ‘expression’ becomes False, the loop finishes. The keyword end specifies the ending of while loop.

### Code

In the code below, the while loop runs five times (from $0$ to $4$) and ends as soon as the ‘count’ equals $5$.

count = 0;

while( count < 5 )
fprintf('The count is \n', count);
count = count + 1;
end
The example code of while loop in MATLAB

### Output

The output is:

The count is 0
The count is 1
The count is 2
The count is 3
The count is 4


### For loop

For loop can be defined in the following two ways:

#### Example 1

The for loop starts its execution from startCount and ends at endCount.

Note: Both the counts are inclusive in this case.

Similar to while loop, the keyword end specifies the end of for loop.

// increment from start to end
for i = startCount:endCount
code
end
The syntax of for loop in MATLAB

#### Example 2

For for loop with step value, the start counter increments is based on the ‘step’ value till the end counter.

// increment or decrement from start to end based on
// step value
for i = startCount:step:endCount
code
end
The syntax of for loop in MATLAB

### Code

#### Implementation of example 1

The following example shows that the print statement is executed five times from $1$ to $5$, inclusive. As the count reaches $5$, the for loop ends.

for count = 1:5
fprintf('The value of count is \n', count);
end
The example code of for loop in MATLAB

#### Output

The output is:

The value of count is 1
The value of count is 2
The value of count is 3
The value of count is 4
The value of count is 5


#### Implementation of example 2

In the second example, the for loop increments by step value which is $2$, and reaches the end counter, which is $12$.

for count = 2:2:12
fprintf('The value of count is \n', count);
end
The example code of for loop in MATLAB

#### Output

The output is:

The value of count is 2
The value of count is 4
The value of count is 6
The value of count is 8
The value of count is 10
The value of count is 12


### Conclusion

The main difference between the for and while loop in MATLAB is that for loop does not require the counter to be incremented manually, but the while loop does.

RELATED TAGS

matlab
communitycreator

CONTRIBUTOR

Mahnoor Zaheer
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time