What are the types of loops in MATLAB?

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

Example program

In the code below, the while loop runs five times (from 00 to 44) and ends as soon as the ‘count’ equals 55.

count = 0;
while(count < 5)
fprintf('The count is %d\n', count);
count = count + 1;
end

For loop

For loop can be defined in the following two ways:

Syntax type 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

Syntax type 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

Code implementation

The syntaxes mentioned above are implemented as follows:

Implementation of syntax 1

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

for count = 1:5
fprintf('The value of count is %d\n', count);
end

Implementation of syntax 2

In the second example, the for loop increments by step value which is 22, and reaches the end counter, which is 1212.

for count = 2:2:12
fprintf('The value of count is %d\n', count);
end

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.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved