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:
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
.
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 can be defined in the following two ways:
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
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
The syntaxes mentioned above are implemented as follows:
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
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
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