Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

matlab
communitycreator

What are the loop control statements in MATLAB?

Mahnoor Zaheer

Overview

In MATLAB, we use the loop control statements to alter the execution of loops. There are two loop control statements. These are described below:

  1. The break statement
  2. The continue statement

1. The break statement

In MATLAB, the break statement terminates the execution of a loop and shifts the execution to the code after the loop.

Illustration for break statement

Example

count = 0;
while count < 10
  if count > 7
      break;
      // terminate the loop 
  fprintf('The value of count is \n', count);
end 

// The output is:
// The value of count is 0
// 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 6
// The value of count is 7
The example code of break statement in MATLAB

Explanation

In the example above, we use the break statement to terminate the while loop as the count exceeds 7. This is why the output is only generated till count=7.

2. The continue statement

We use the continue statement to skip the iteration of a loop. Also, it helps execute the loop from the next iteration onwards.

Illustration for the continue statement

Example

count = 0;
while count < 10
  if count == 5
      continue;
      // skip the iteration 
  fprintf('The value of count is \n', count);
end 

// The output is:
// The value of count is 0
// 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 6
// The value of count is 7
// The value of count is 8
// The value of count is 9
The example code of continue statement in MATLAB

Explanation

We use the continue statement so that the while loop skips an iteration when the count equals 5. Therefore, the output does not display the count value of 5 and continues from 6 onwards.

RELATED TAGS

matlab
communitycreator
RELATED COURSES

View all Courses

Keep Exploring