KAHIBARO Bookshelves
Discord Login Register

5.3. Loops with for and while

Why Loops Are Useful

Loops let you repeat a block of code several times without copying and pasting the same commands. They are essential when you need to perform the same operation on many values, such as processing all elements of a vector, running a simulation for many time steps, or repeating a calculation until a condition is met.

In MATLAB, the two basic loop types are for and while. They both repeat code, but they are used in slightly different situations.

The Structure of a for Loop

A for loop repeats a block of code a fixed number of times. You specify a loop variable and the set of values that this variable should take. MATLAB automatically steps through these values, one by one.

The general form of a for loop is:

for index = values
    statements
end

The keyword for starts the loop. The variable index is the loop variable that changes each time. The right side values is typically a vector. MATLAB sets index to each element of values in turn, then runs the statements block each time. The keyword end finishes the loop block.

As a simple example, you can display the numbers from 1 to 5:

for k = 1:5
    disp(k)
end

Here, 1:5 creates the vector [1 2 3 4 5], and k takes those values, one by one. The command disp(k) is run five times.

Using Different Ranges and Steps in for Loops

The vector that defines the loop values can use any start, step, and end that you can represent with the colon operator. This gives you control over how many iterations run and what values the loop variable takes.

For example, you can count by twos:

for n = 0:2:10
    disp(n)
end

Here, 0:2:10 produces [0 2 4 6 8 10]. The loop runs six times, and n takes each of these even numbers.

You can also iterate over a vector that you define separately:

v = [10 20 50 100];
for x = v
    disp(x)
end

The loop runs four times, once for each element of v. The loop variable can have any valid name. Using a short, descriptive name often makes your code easier to read.

Building Results Inside for Loops

A common use of for loops is to fill or update arrays element by element. Inside the loop, you often use the loop variable as an index.

For instance, to create a vector of squares of the first 5 integers:

n = 5;
squares = zeros(1, n);   % preallocate a row vector
for k = 1:n
    squares(k) = k^2;
end

Each iteration sets one element of squares. Preallocating the array before the loop, as shown with zeros, avoids changing the size of the array repeatedly inside the loop, which improves performance. Details about efficient code and performance are covered elsewhere, but it is helpful to see this common pattern when you start writing loops.

You can also accumulate a single value. For example, a simple sum:

total = 0;
for k = 1:10
    total = total + k;
end

At the end of the loop, total holds the sum of integers from 1 to 10.

Nested for Loops

You can place one for loop inside another. This is called a nested loop. It is often used when you work with 2D data, such as matrices, and want to move along rows and columns.

For a simple example, consider printing the indices of a small 2 by 3 grid:

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

The outer loop controls i, and for each value of i, the inner loop runs through all values of j. The total number of iterations is the product of the lengths of the two ranges. Nested loops are powerful, but can become slow if you nest many levels or use very large ranges.

The Structure of a while Loop

A while loop repeats a block of code as long as a logical condition is true. Unlike the for loop, you do not specify in advance how many times the loop will run. The loop continues until the condition becomes false.

The general form of a while loop is:

while condition
    statements
end

The condition is an expression that MATLAB can evaluate as true or false, usually through relational and logical operators. If the condition is true, MATLAB runs the statements block, then checks the condition again, and repeats. When the condition becomes false, MATLAB exits the loop and continues with the code after end.

For example, you can double a number until it exceeds 100:

x = 1;
while x <= 100
    x = x * 2;
end

At each iteration, MATLAB checks whether x <= 100. If the condition is true, it multiplies x by 2 and then checks again. Eventually x becomes larger than 100, the condition becomes false, and the loop ends.

Controlling Progress in while Loops

To use while safely, you must make sure that something inside the loop changes in a way that will eventually make the condition false. Otherwise, your loop can run without end.

A typical pattern is to update a variable that appears in the loop condition. For example, this loop counts from 1 to 5 in a way similar to a for loop:

k = 1;
while k <= 5
    disp(k)
    k = k + 1;
end

Here, k starts at 1. Inside the loop, it is incremented by 1 each time. Eventually, k becomes 6, the condition k <= 5 is false, and the loop stops.

You can also combine several conditions. For instance, suppose you want to iterate until a value is large enough or until you reach a maximum number of steps:

x = 0.5;
step = 0;
maxSteps = 20;
while x < 10 && step < maxSteps
    x = x * 1.5;
    step = step + 1;
end

Here you use a logical && operator to require both conditions to be true. The loop stops if x reaches or exceeds 10, or if step reaches 20, whichever comes first.

When to Use for vs while

Even though both for and while can be used to repeat work, they are suited to different kinds of problems.

Use a for loop when you know in advance how many iterations you need, or when you naturally have a vector of values that you want to loop over. Examples include processing each element of a known-size array, or running a fixed number of simulation steps.

Use a while loop when the number of iterations depends on a condition that is evaluated during the loop. Examples include iterating until a value converges, waiting for a certain threshold, or running until user input matches a requirement.

Often, the same task can be written with either type. In those cases, consider which structure makes the intention clearer to a reader of your code. Clarity is usually more important than small differences in performance.

Avoiding Infinite Loops

An infinite loop is a loop that never ends. This usually happens when the loop condition stays true forever. Infinite loops can occur with both for and while, but are more common with while loops because the number of iterations is not fixed.

To avoid infinite loops with while:

Ensure that at least one variable in the condition is updated inside the loop in a way that will eventually make the condition false. For example, if your condition is k < 100, then k needs to grow or change.

Consider adding a safety limit, such as a maximum number of iterations, especially in early versions of your code. For example, maintain a counter and include it in the condition.

If you accidentally start a loop that you want to stop while it is running, you can interrupt execution in MATLAB by pressing Ctrl+C in the Command Window.

Even with for loops, you can create large computations that appear as if they never end, for example if you loop over a very large range or if the work inside the loop is very slow. In such situations, check your loop limits and see whether you can simplify or partly vectorize your code.

Important things to remember:
Use for when you know the set of values or number of iterations in advance. Use while when you need to repeat until a condition is met.
Always make sure that something in a while loop changes so the condition will eventually become false. Otherwise, you risk an infinite loop.
Preallocate arrays before filling them in loops to avoid growing arrays one element at a time.
Nested loops can be powerful but costly. Be careful with deeply nested loops or very large iteration ranges.

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