0
0
MatlabHow-ToBeginner ยท 3 min read

How to Use break in MATLAB: Syntax and Examples

In MATLAB, use the break statement to immediately exit a for or while loop. When MATLAB encounters break, it stops the current loop and continues with the code after the loop.
๐Ÿ“

Syntax

The break statement is used inside loops to stop the loop immediately. It has no arguments and is simply written as break.

Use it inside for or while loops to exit early based on a condition.

matlab
for i = 1:10
    if i == 5
        break
    end
    disp(i)
end
Output
1 2 3 4
๐Ÿ’ป

Example

This example shows a for loop that prints numbers from 1 to 10 but stops when the number reaches 5 using break.

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

Common Pitfalls

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

Another mistake is forgetting to use break inside an if condition, so the loop never stops early.

matlab
x = 1;
if x == 1
    break  % This will cause an error because break is outside a loop
end

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

Quick Reference

break stops the nearest enclosing loop immediately and continues with the code after the loop.

  • Use inside for or while loops only.
  • No arguments needed.
  • Commonly used with if to exit loops early.
โœ…

Key Takeaways

Use break inside loops to exit them immediately.
break works only within for or while loops.
Place break inside an if condition to stop loops early based on logic.
Using break outside loops causes errors.
After break, MATLAB continues with the code following the loop.