0
0
MatlabHow-ToBeginner ยท 3 min read

How to Use Continue in MATLAB: Syntax and Examples

In MATLAB, use the continue statement inside loops to skip the remaining code in the current iteration and move to the next iteration immediately. It works with for and while loops to control loop flow efficiently.
๐Ÿ“

Syntax

The continue statement is used inside a loop to skip the rest of the current iteration and jump to the next iteration.

It can be used in both for and while loops.

  • continue: Skips remaining code in the loop body for the current iteration.
matlab
for i = 1:5
    if i == 3
        continue
    end
    disp(i)
end
Output
1 2 4 5
๐Ÿ’ป

Example

This example shows a for loop from 1 to 5. When the loop variable is 3, the continue statement skips printing 3 and moves to the next iteration.

matlab
for i = 1:5
    if i == 3
        continue
    end
    disp(i)
end
Output
1 2 4 5
โš ๏ธ

Common Pitfalls

One common mistake is placing continue outside of a loop, which causes an error because continue only works inside loops.

Another mistake is forgetting that continue skips only the current iteration, not the entire loop.

matlab
x = 1;
if x == 1
    continue % This will cause an error because it's outside a loop
end

% Correct usage:
for i = 1:3
    if i == 2
        continue % Skips printing 2
    end
    disp(i)
end
Output
1 3
๐Ÿ“Š

Quick Reference

KeywordDescription
continueSkips the rest of the current loop iteration and moves to the next iteration
forDefines a loop with a fixed number of iterations
whileDefines a loop that runs while a condition is true
โœ…

Key Takeaways

Use continue inside loops to skip the current iteration and proceed to the next.
continue works only within for and while loops in MATLAB.
Placing continue outside a loop causes an error.
It helps control loop flow by avoiding unnecessary code execution in some iterations.