KAHIBARO Bookshelves
Discord Login Register

5.4. break, continue, and return

Controlling Loop Execution with `break`, `continue`, and `return`

In MATLAB, loops normally run until their loop condition is no longer satisfied. Sometimes you want to stop a loop early, skip part of a loop, or stop running a function entirely. The commands break, continue, and return give you fine control over this behavior. They are small keywords, but they change the flow of execution in important ways.

This chapter focuses only on how these three commands behave inside loops and functions, and how you can use them safely in beginner level programs.

The `break` Statement

The break statement stops the execution of the innermost loop that contains it. As soon as MATLAB executes break, it exits that loop immediately and continues with the next line of code after the loop.

Consider a for loop that searches for the first number greater than 10 in a vector. You can stop the loop once the value is found.

v = [2 5 9 12 15 3 18];
foundIndex = NaN;
for k = 1:length(v)
    if v(k) > 10
        foundIndex = k;
        break
    end
end
disp(foundIndex)

Here the loop was originally set to run from k = 1 to k = length(v). The break statement shortens the loop at runtime. After a value greater than 10 is found, MATLAB immediately leaves the loop and continues with disp(foundIndex).

If you have nested loops, break only exits the innermost loop where it appears. It does not exit any outer loop.

for i = 1:3
    for j = 1:5
        if j == 3
            break
        end
        fprintf('i = %d, j = %d\n', i, j);
    end
end

In this example the break stops only the j loop. The i loop continues with the next value of i. So, for each i, j will run only for 1 and 2.

You can also use break in a while loop. This is common when the loop condition cannot easily be written in a single logical expression.

x = 0;
while true
    x = x + 1;
    if x^2 > 50
        break
    end
end
disp(x)

Here while true creates an infinite loop in theory. In practice, the break condition inside the loop controls when the loop stops. This pattern is useful when you do not know in advance how many iterations are needed.

The `continue` Statement

The continue statement does not end the entire loop. Instead, it skips the rest of the current iteration and jumps directly to the next iteration of the loop.

This is helpful when you want to ignore certain values or cases without stopping the loop completely.

Suppose you want to sum only the positive elements of a vector. You can use continue to skip all nonpositive numbers.

v = [3 -1 4 0 5 -2];
s = 0;
for k = 1:length(v)
    if v(k) <= 0
        continue
    end
    s = s + v(k);
end
disp(s)

When v(k) is less than or equal to zero, MATLAB executes continue. It then ignores any remaining statements in the loop body for that iteration, and proceeds with the next value of k. The assignment s = s + v(k) is only executed when v(k) is positive.

You can also combine continue with multiple conditions. Sometimes this simplifies your loop by keeping special cases at the top and the main logic at the bottom.

for n = 1:10
    if mod(n,2) == 1
        continue
    end
    fprintf('Even number: %d\n', n);
end

In this loop, when n is odd the continue skips the printing statement, so only even numbers are displayed.

As with break, when loops are nested, continue affects only the innermost loop that contains it.

for i = 1:3
    for j = 1:5
        if j == 2
            continue
        end
        fprintf('i = %d, j = %d\n', i, j);
    end
end

In this example, the continue skips the body of the inner loop only when j == 2. The outer loop over i is unaffected.

You can use continue in while loops in the same way.

x = 0;
while x < 5
    x = x + 1;
    if x == 3
        continue
    end
    fprintf('x = %d\n', x);
end

Because of continue, the value 3 is not printed, while the loop continues for x = 4 and x = 5.

The `return` Statement

The return statement exits the current function and returns control to the caller. Execution continues with the line immediately after the function call.

When return appears inside a function file, MATLAB stops executing that function as soon as it reaches return. Any remaining lines in that function are not executed. If the function has output variables, their current values at the moment of return are passed back.

Consider a simple function that divides two numbers but handles division by zero specially.

function q = safeDivide(a, b)
    if b == 0
        q = NaN;
        return
    end
    q = a / b;
end

If the user calls safeDivide(5, 0), the body of the function sets q = NaN, executes return, and immediately exits. The line q = a / b; never runs, so division by zero is avoided. If b is not zero, the if condition is false, the return is skipped, and the function continues normally.

You can also use return inside loops that are inside functions. In that case, return exits the entire function, not just the loop.

function idx = findFirstNegative(v)
    idx = NaN;
    for k = 1:length(v)
        if v(k) < 0
            idx = k;
            return
        end
    end
end

Here the function stops as soon as it finds a negative value. The return leaves both the for loop and the function at once.

If a script file (not a function) contains return, MATLAB stops executing that script and returns to the Command Window or to the calling script or function. This is less common for beginners, but it can be used to exit a long script early.

Choosing Between `break`, `continue`, and `return`

break, continue, and return all change the normal flow of execution, but they act at different levels.

Use break when you want to stop a loop early, but still continue executing the code that follows the loop. This is typical for search tasks, where you only need the first match.

Use continue when you want the loop to keep running, but you want to skip the remaining lines in the body for specific iterations. This keeps the main logic of the loop simple and avoids deep nesting of if statements.

Use return only in functions or scripts when you want to exit completely from the current function or script. With functions, this often appears as an early exit, for example when input arguments fail a simple check or when a special case is encountered.

It is important to avoid overusing these commands especially once your code becomes more complex. Having many exit points inside loops and functions can make code harder to follow. For small, clear cases, however, they can make code shorter and easier to read.

Important points to remember:
break exits only the innermost loop and continues with the first line after that loop.
continue skips the rest of the current iteration of the innermost loop and starts the next iteration.
return exits the current function or script immediately and continues after the call site.
In nested loops, both break and continue affect only the loop they are directly inside.
Use these commands for clear and simple control flow, but avoid making your code hard to read with too many early exits.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Getting Started with MATLAB
    • ☰ 1.1. What Is MATLAB and What Is It Used For
      • ☰ 1.2. Installing MATLAB and Setting Up the Environment
        • ☰ 1.3. Understanding the MATLAB Desktop Interface
          • ☰ 1.4. Command Window, Workspace, and Current Folder
            • ☰ 1.5. Basic Workflow and Running Simple Commands
              • ☰ 1.6. Getting Help and Documentation
              • ☰ 2. MATLAB Language Basics
                • ☰ 2.1. MATLAB Syntax and Expressions
                  • ☰ 2.2. Variables and Assignment
                    • ☰ 2.3. Data Types and Type Conversion
                      • ☰ 2.4. Vectors and Matrices Fundamentals
                        • ☰ 2.5. Creating and Indexing Arrays
                          • ☰ 2.6. Basic Arithmetic and Elementwise Operations
                            • ☰ 2.7. Using Built-In Constants and Functions
                            • ☰ 3. Working with Variables and the Workspace
                              • ☰ 3.1. Creating, Viewing, and Editing Variables
                                • ☰ 3.2. Workspace Browser and Variable Inspector
                                  • ☰ 3.3. Saving and Loading Data Files
                                    • ☰ 3.4. MAT-Files and Importing External Data
                                      • ☰ 3.5. Clearing Variables and Managing the Workspace
                                      • ☰ 4. Vectors, Matrices, and Arrays
                                        • ☰ 4.1. Row and Column Vectors
                                          • ☰ 4.2. Matrix Creation and Concatenation
                                            • ☰ 4.3. Indexing, Slicing, and Logical Indexing
                                              • ☰ 4.4. Matrix Operations vs Elementwise Operations
                                                • ☰ 4.5. Reshaping and Rearranging Arrays
                                                  • ☰ 4.6. Special Matrices and Functions
                                                  • ☰ 5. Basic Programming Constructs
                                                    • ☰ 5.1. Scripts vs Functions
                                                      • ☰ 5.2. Control Flow with if, elseif, else
                                                        • ☰ 5.3. Loops with for and while
                                                          • ☰ 5.4. break, continue, and return
                                                            • ☰ 5.5. Logical Expressions and Relational Operators
                                                              • ☰ 5.6. Best Practices for Clear and Readable Code
                                                              • ☰ 6. Functions in MATLAB
                                                                • ☰ 6.1. Creating Simple Functions
                                                                  • ☰ 6.2. Function Inputs and Outputs
                                                                    • ☰ 6.3. Function Files and the Path
                                                                      • ☰ 6.4. Local vs Global Variables
                                                                        • ☰ 6.5. Anonymous Functions
                                                                          • ☰ 6.6. Organizing Code into Multiple Functions
                                                                          • ☰ 7. Working with Numbers and Math
                                                                            • ☰ 7.1. Scalars and Vectorized Computations
                                                                              • ☰ 7.2. Basic Mathematical Functions
                                                                                • ☰ 7.3. Trigonometric and Exponential Functions
                                                                                  • ☰ 7.4. Complex Numbers in MATLAB
                                                                                    • ☰ 7.5. Rounding, Modulo, and Special Values
                                                                                      • ☰ 7.6. Numerical Precision and Floating Point Considerations
                                                                                      • ☰ 8. Strings, Characters, and Categorical Data
                                                                                        • ☰ 8.1. Character Arrays and String Arrays
                                                                                          • ☰ 8.2. Creating and Manipulating Strings
                                                                                            • ☰ 8.3. Converting Between Data Types and Strings
                                                                                              • ☰ 8.4. Comparing and Searching Strings
                                                                                                • ☰ 8.5. Categorical Arrays Basics
                                                                                                • ☰ 9. Tables, Structures, and Cell Arrays
                                                                                                  • ☰ 9.1. Introduction to Tables
                                                                                                    • ☰ 9.2. Creating Tables and Accessing Data
                                                                                                      • ☰ 9.3. Modifying and Joining Tables
                                                                                                        • ☰ 9.4. Structures and Nested Structures
                                                                                                          • ☰ 9.5. Cell Arrays and Cell Indexing
                                                                                                            • ☰ 9.6. Choosing the Right Container Type
                                                                                                            • ☰ 10. Importing and Exporting Data
                                                                                                              • ☰ 10.1. Reading Text and CSV Files
                                                                                                                • ☰ 10.2. Importing Excel Spreadsheets
                                                                                                                  • ☰ 10.3. Importing Data with the Import Tool
                                                                                                                    • ☰ 10.4. Exporting Data to Files
                                                                                                                      • ☰ 10.5. Working with Image and Audio Files
                                                                                                                        • ☰ 10.6. Basic File Management from MATLAB
                                                                                                                        • ☰ 11. Plotting and Visualization
                                                                                                                          • ☰ 11.1. Introduction to 2D Plotting
                                                                                                                            • ☰ 11.2. Customizing Plots and Axes
                                                                                                                              • ☰ 11.3. Multiple Plots in One Figure
                                                                                                                                • ☰ 11.4. Labels, Titles, Legends, and Annotations
                                                                                                                                  • ☰ 11.5. Plotting with Different Line and Marker Styles
                                                                                                                                    • ☰ 11.6. Saving and Exporting Figures
                                                                                                                                    • ☰ 12. Advanced Plotting for Beginners
                                                                                                                                      • ☰ 12.1. Subplots and Tiled Layouts
                                                                                                                                        • ☰ 12.2. Bar, Scatter, and Stem Plots
                                                                                                                                          • ☰ 12.3. Histograms and Density Plots
                                                                                                                                            • ☰ 12.4. 3D Plots and Surface Plots
                                                                                                                                              • ☰ 12.5. Using plottools and Interactive Editing
                                                                                                                                                • ☰ 12.6. Basics of Handle Graphics
                                                                                                                                                • ☰ 13. Working with Scripts and Live Scripts
                                                                                                                                                  • ☰ 13.1. Creating and Running Script Files
                                                                                                                                                    • ☰ 13.2. Sectioning Code and Running Sections
                                                                                                                                                      • ☰ 13.3. Live Scripts and Rich Text
                                                                                                                                                        • ☰ 13.4. Adding Equations, Images, and Outputs
                                                                                                                                                          • ☰ 13.5. Sharing and Exporting Live Scripts
                                                                                                                                                          • ☰ 14. Debugging and Code Quality
                                                                                                                                                            • ☰ 14.1. Finding and Fixing Syntax Errors
                                                                                                                                                              • ☰ 14.2. Setting Breakpoints and Stepping Through Code
                                                                                                                                                                • ☰ 14.3. Inspecting Variable Values During Execution
                                                                                                                                                                  • ☰ 14.4. Using the Editor Debugging Tools
                                                                                                                                                                    • ☰ 14.5. Using Code Analyzer and Warnings
                                                                                                                                                                      • ☰ 14.6. Writing Clean and Maintainable MATLAB Code
                                                                                                                                                                      • ☰ 15. Basic Linear Algebra with MATLAB
                                                                                                                                                                        • ☰ 15.1. Vectors and Norms
                                                                                                                                                                          • ☰ 15.2. Matrix Addition and Multiplication
                                                                                                                                                                            • ☰ 15.3. Solving Linear Systems with Backslash
                                                                                                                                                                              • ☰ 15.4. Inverses, Determinants, and Rank
                                                                                                                                                                                • ☰ 15.5. Eigenvalues and Eigenvectors
                                                                                                                                                                                  • ☰ 15.6. Using Linear Algebra Functions Safely
                                                                                                                                                                                  • ☰ 16. Data Analysis and Statistics Fundamentals
                                                                                                                                                                                    • ☰ 16.1. Descriptive Statistics and Summary Measures
                                                                                                                                                                                      • ☰ 16.2. Sorting, Filtering, and Grouping Data
                                                                                                                                                                                        • ☰ 16.3. Basic Correlation and Regression
                                                                                                                                                                                          • ☰ 16.4. Simple Data Cleaning Techniques
                                                                                                                                                                                            • ☰ 16.5. Basic Time Series Handling
                                                                                                                                                                                            • ☰ 17. Working with Time and Dates
                                                                                                                                                                                              • ☰ 17.1. Representing Dates and Times
                                                                                                                                                                                                • ☰ 17.2. Creating and Formatting datetime Arrays
                                                                                                                                                                                                  • ☰ 17.3. Date Calculations and Differences
                                                                                                                                                                                                    • ☰ 17.4. Plotting Data over Time
                                                                                                                                                                                                    • ☰ 18. Introduction to Signal and Image Handling
                                                                                                                                                                                                      • ☰ 18.1. Basic Signal Representation in MATLAB
                                                                                                                                                                                                        • ☰ 18.2. Simple Filtering and Transformations
                                                                                                                                                                                                          • ☰ 18.3. Reading, Displaying, and Writing Images
                                                                                                                                                                                                            • ☰ 18.4. Basic Image Transformations
                                                                                                                                                                                                            • ☰ 19. Automation and Scripting Tasks
                                                                                                                                                                                                              • ☰ 19.1. Batch Processing of Files
                                                                                                                                                                                                                • ☰ 19.2. Writing Reusable Utility Scripts
                                                                                                                                                                                                                  • ☰ 19.3. Using Relative Paths and the MATLAB Path
                                                                                                                                                                                                                    • ☰ 19.4. Simple User Interaction with input and disp
                                                                                                                                                                                                                    • ☰ 20. Introduction to Toolboxes
                                                                                                                                                                                                                      • ☰ 20.1. What Are Toolboxes and How to Use Them
                                                                                                                                                                                                                        • ☰ 20.2. Exploring Installed Toolboxes
                                                                                                                                                                                                                          • ☰ 20.3. Finding Functions in Toolboxes
                                                                                                                                                                                                                            • ☰ 20.4. Add-Ons and MATLAB File Exchange
                                                                                                                                                                                                                            • ☰ 21. Best Practices and Next Steps
                                                                                                                                                                                                                              • ☰ 21.1. Organizing Projects and Folders
                                                                                                                                                                                                                                • ☰ 21.2. Version Control Basics with MATLAB
                                                                                                                                                                                                                                  • ☰ 21.3. Performance Tips for Beginners
                                                                                                                                                                                                                                    • ☰ 21.4. Learning Resources and Documentation Path
                                                                                                                                                                                                                                      • ☰ 21.5. Suggested Practice Projects for Beginners