Kahibaro
Discord Login Register

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: 4

Comments

Please login to add a comment.

Don't have an account? Register now!