LibraryLoops: `for`, `while`, `break`, `continue`

Loops: `for`, `while`, `break`, `continue`

Learn about Loops: `for`, `while`, `break`, `continue` as part of MATLAB Programming for Engineering and Scientific Research

Mastering Loops in MATLAB: `for`, `while`, `break`, and `continue`

Loops are fundamental control flow structures in programming that allow you to execute a block of code repeatedly. In MATLAB,

code
for
and
code
while
loops are essential for automating repetitive tasks, processing data collections, and implementing algorithms in engineering and scientific research.

The `for` Loop: Iterating a Fixed Number of Times

A

code
for
loop is ideal when you know in advance how many times you want to repeat a set of operations. It iterates over a sequence, such as a vector or a range of numbers.

The `for` loop executes code a predetermined number of times.

Use for loops to iterate through a sequence of values. The loop variable takes on each value in the sequence one by one.

The basic syntax for a for loop in MATLAB is:

for variable = start:step:end
    % Code to be executed in each iteration
end

If step is omitted, it defaults to 1. You can also iterate over a vector:

myVector = [10, 20, 30, 40];
for element = myVector
    disp(element);
end

This will display each element of myVector on a new line.

When is a for loop the most appropriate choice for iteration?

When the number of iterations is known in advance or when iterating over a defined sequence.

The `while` Loop: Iterating Based on a Condition

A

code
while
loop continues to execute a block of code as long as a specified condition remains true. This is useful when the number of iterations is not known beforehand and depends on a dynamic condition.

The `while` loop repeats as long as a condition is met.

A while loop checks a condition before each iteration. If the condition is true, the loop body executes; otherwise, it terminates.

The syntax for a while loop is:

while condition
    % Code to be executed as long as the condition is true
end

It's crucial to ensure that the condition eventually becomes false to avoid an infinite loop. This typically involves updating a variable within the loop that affects the condition.

Example:

count = 1;
while count <= 5
    disp(['Iteration: ', num2str(count)]);
    count = count + 1; % Update the counter
end
What is the primary risk associated with while loops, and how can it be mitigated?

The risk is an infinite loop. It can be mitigated by ensuring the loop's condition eventually becomes false, usually by updating a variable within the loop.

Controlling Loop Execution: `break` and `continue`

MATLAB provides

code
break
and
code
continue
statements to exert finer control over loop execution, allowing you to exit a loop prematurely or skip the rest of the current iteration.

StatementActionEffect on Loop
breakImmediately terminates the current loop.The loop stops executing entirely, and control passes to the statement following the loop.
continueSkips the remaining statements in the current iteration.The loop proceeds to the next iteration (if the loop condition is still met).

Example using

code
break
and
code
continue
:

matlab
for i = 1:10
if i == 3
continue; % Skip iteration when i is 3
end
if i == 7
break; % Exit loop when i is 7
end
disp(i);
end

This code will display numbers 1, 2, 4, 5, and 6. It skips 3 due to

code
continue
and stops at 7 due to
code
break
.

Visualizing loop control flow: Imagine a conveyor belt (the loop) carrying items (iterations). continue is like taking an item off the belt and putting it aside without processing the rest of its journey. break is like stopping the entire conveyor belt, regardless of what items are still on it.

📚

Text-based content

Library pages focus on text content

Be mindful of infinite loops! Always ensure your while loop conditions will eventually evaluate to false, and use break judiciously to exit loops when necessary.

Learning Resources

MATLAB Documentation: For Loops(documentation)

Official MathWorks documentation detailing the syntax, usage, and examples of `for` loops in MATLAB.

MATLAB Documentation: While Loops(documentation)

Comprehensive guide from MathWorks on `while` loops, including their structure and common applications.

MATLAB Documentation: Break Statement(documentation)

Explains how to use the `break` statement to exit loops prematurely in MATLAB.

MATLAB Documentation: Continue Statement(documentation)

Details the functionality of the `continue` statement for skipping loop iterations.

MATLAB Programming Tutorial: Loops(tutorial)

A beginner-friendly tutorial covering `for` and `while` loops with practical examples.

Introduction to MATLAB Programming - Loops(video)

A video tutorial demonstrating the concepts of `for` and `while` loops in MATLAB with visual explanations.

MATLAB Control Flow: Loops and Conditional Statements(blog)

An article explaining control flow structures in MATLAB, with a focus on loops and their practical use cases.

MATLAB Loops: For, While, Break, Continue(blog)

A clear explanation of MATLAB loop constructs and control statements with code examples.

MATLAB Fundamentals: Control Flow(tutorial)

An interactive tutorial from MathWorks covering essential control flow concepts, including loops.

MATLAB Loop Examples for Scientific Computing(documentation)

A collection of practical MATLAB code examples demonstrating loop usage in scientific and engineering contexts.