0
0
MATLABdata~5 mins

Break and continue in MATLAB

Choose your learning style9 modes available
Introduction

Break and continue help control loops by stopping or skipping steps. They make your code smarter and faster.

Stop a loop when you find the answer you want.
Skip a step in a loop if it doesn't meet a condition.
Exit a loop early to save time.
Ignore certain values while looping through data.
Control complex loops with simple commands.
Syntax
MATLAB
for i = 1:n
    if condition
        break
    end
    % other code
end

for i = 1:n
    if condition
        continue
    end
    % other code
end

break stops the whole loop immediately.

continue skips the rest of the current loop step and moves to the next one.

Examples
This loop stops when i is 3, so it prints 1 and 2 only.
MATLAB
for i = 1:5
    if i == 3
        break
    end
    disp(i)
end
This loop skips printing 3 but prints all other numbers from 1 to 5.
MATLAB
for i = 1:5
    if i == 3
        continue
    end
    disp(i)
end
Sample Program

This program loops from 1 to 10. It stops completely when i reaches 6. It skips even numbers and only prints odd numbers before 6.

MATLAB
for i = 1:10
    if i == 6
        break
    end
    if mod(i,2) == 0
        continue
    end
    disp(i)
end
OutputSuccess
Important Notes

Use break carefully to avoid stopping loops too early.

continue only skips the current step, not the whole loop.

Both commands help make loops more efficient and clear.

Summary

break stops the entire loop immediately.

continue skips the current loop step and moves on.

They help control loops to run smarter and faster.