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:
- While loop
- For loop
While loop
The syntax of this loop is:
while (expression)codeend
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 to ) and ends as soon as the ‘count’ equals .
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 endfor i = startCount:endCountcodeend
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 valuefor i = startCount:step:endCountcodeend
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 to , inclusive. As the count reaches , the for loop ends.
for count = 1:5fprintf('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 , and reaches the end counter, which is .
for count = 2:2:12fprintf('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