Real Technology Tools

For Loop Syntax in MATLAB Through Simple Examples

In this article, you’ll see practical examples of MATLAB for loops so that you can become more familiar with the way they work in MATLAB. Specifically, you’ll learn:

MATLAB For Loop Syntax

Creating a Simple For Loop in MATLAB

There are several ways of writing a for loop in MATLAB. Here’s the most common example you’ll use to write a for loop:

for i = 1:n % n is the number of loops you want
     instructions; % what you want to do n times 
end

MATLAB For Loop Backwards

In this case, a few things differ from a classic “forward” MATLAB for loop:

Here’s an example of a for loop that counts backward from 10 to 1:

for i = 10:-1:1 % "-1" is the decrement step
     i
end

Exit a For Loop with a Break

Nested For Loop In MATLAB

Nested For Loop Example

As we saw before, a nested for loop is a loop within a loop. In MATLAB, you can define as many nested for loops as you want by using the following (for only 2 levels of nested for loops):

for i = 1:n
    for j = 1:m
        instructions
    end
end

Here’s a simple an example:

k = 0;
for i = 1:10
    for j = 1:10
        k = k+i+j;
    end
end

In mathematical terms, we are calculating the sum: \(\sum\limits_{i=1}^{n}\sum\limits_{j=1}^{n}(i+j)\)

Which can be calculated as the following:

\(\sum\limits_{i=1}^{n}\sum\limits_{j=1}^{n}(i+j) = \sum\limits_{i=1}^{n}(\sum\limits_{j=1}^{n}i+\sum\limits_{j=1}^{n}j)=\sum\limits_{i=1}^{n}(i\times n +\frac{n(n+1)}{2})\\\\\sum\limits_{i=1}^{n}(i\times n +\frac{n(n+1)}{2})=n\sum\limits_{i=1}^{n}i+\sum\limits_{i=1}^{n}\frac{n(n+1)}{2}=\frac{n^2(n+1)}{2}+\frac{n^2(n+1)}{2} = n^2(n+1)\)

If you take n=10,

\(n^2(n+1) = 10^2\times11=1100\)

Which is what you get in MATLAB:

Exit a Nested for loop

Which gives us the following in MATLAB:

Remember, k doesn’t iterate in single increments, so it makes sense that next iteration of k isn’t 501.

Vectorize Nested Loops

What Does it Mean?

This involves transforming a nested loop in a multiplication of vectors or matrices to optimize the run time. It is also more elegant to use arrays instead of for loops when it’s not necessary.

How to Vectorize a For Loop: Basic Example

Let’s say we want to compute the sum \(\sum\limits_{i=1}^{n}\sum\limits_{j=1}^{n}(i\times j)\). We can use a nested for loop to do the following:

for i = 1:10
    for j = 1:10
        k = k+i*j;
    end
end

If you run this script in MATLAB, you get:

Instead of using this nested for loop, you can use the following arrays:

A = 1:10;
B = [A ; A ; A ; A ; A ; A ; A ; A ; A ; A];
C = ones(10, 1);

The multiplication of these arrays (A*B*C) is equivalent to the nested for loop but is more elegant and faster to compute.

Example: Vectorize a For Loop For a Sum of Squared Elements

You can also vectorize the sum from i to n of i^2 by using element-wise operations on a vector:

i = 1:100;
S = sum(i.^2);

This example is detailed in the following article: MATLAB Vector Tutorial: Create, Add, Concatenate, and Extract

Key takeaways:

  1. Use this syntax to define a for loop in MATLAB:
    for i = 1:n % n is the number of loops you want
         instructions; % what you want to do n times 
    end
  2. Use this syntax to define nested for loops in MATLAB:
    for i = 1:n
        for j = 1:m
            instructions
        end
    end
  3. Vectorizing Nested for loops:
    • You can vectorize a nested for loop to optimize your code
    • Here’s an example:
      for i = 1:10
          for j = 1:10
              k = k+i*j;
          end
      end

      If you vectorize this nested for loop, you get:

      A = 1:10;
      B = [A ; A ; A ; A ; A ; A ; A ; A ; A ; A];
      C = ones(10, 1);
      k = A*B*C;

If you want to learn more about the tools that helped me stop wasting time doing mindless work (such as generating Excel reports, Word documents, or creating clean and simple user interfaces) I wrote a small reference book about it:

 

 

Exit mobile version