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:

• The MATLAB for loop syntax
• The Nested for loop syntax
• How to vectorize nested loops

## 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
• Example of a loop that counts to 10:
for i = 1:10
i
end
• Example of a loop that creates a cell array of numbers:
cellArrayOfNumbers = [];
for i = 1:10
cellArrayOfNumbers = [cellArrayOfNumbers {i}]; % cell of the number of iterations
end

This for loop creates a cell array of 1 line and 10 rows with all iterations of the loop:

• Example of a loop that creates a cell array of strings:
cellArrayOfStrings = [];
for i = 1:10
cellArrayOfStrings = [cellArrayOfStrings {'string'}]; % cell of the word 'string'
end

This for loop creates a cell array of 1 line and 10 rows with the word “string” in every cell:

• Example of a for loop that counts to 10 in 0.1 increments:
for i = 1:0.1:10 % "0.1" is the increment step
i
end

Since the increment step can be whatever you want, you can also use it to create backward loops (as we will see in the next section).

### MATLAB For Loop Backwards

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

• The iteration step is negative.
• The number at the left of the first colon is greater than the number at the right of the last colon.

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

• Exit a for loop: if you want to prematurely escape a for loop, you can do that by using the break MATLAB function. This is often used when a specific condition is met.
For example:
for i = 1:100
if i>50
break
end
end
• Why use a break: If you run the code above, you’ll get the value 51 for the variable “i” since the for loop stops or “breaks” as soon as i is strictly above 50.
Keep in mind that this is a simple example, and using the break MATLAB command here is really not recommended because you could just write this instead:
for i = 1:51
end

Using break comes in handy when you have nested for loops (i.e. a for loop within a for loop) because you can exit a loop based on a condition that is common to both loops.

## 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

• Syntax: unfortunately, there is no elegant way (that I know of) to exit every nested loop and execute the rest of the code. You basically need to repeat the condition every time you want to exit a for loop:
for i = 1:n
for j = 1:m
instructions
if breakCondition
break
end
end
if breakCondition
break
end
end
• Example: if we take the previous item, we would get:
k = 0;
for i = 1:10
for j = 1:10
k = k+i+j;
breakCondition = k>500;
if breakCondition
break
end
end
if breakCondition
break
end
end

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 practical tips that helped me stop wasting time doing mindless work (such as working with Excel files and writing reports) I wrote a small reference book about it: