Updated June 27, 2023

## Definition of Nested Loop in Matlab

A nested Loop is a compound statement in Matlab where we can place a loop inside the body of another loop, a nested form of a conditional statement. As you know, Matlab allows you to combine compound statements like IF and FOR & WHILE inside other compound loops. This nesting loop is called a nested loop in Matlab. You should note that you can put one type of loop inside a different kind of loop.

Generally, a loop is a repetitive code part that efficiently allows you to execute the conditional statements a specific number of times you need. Thus, a Nested Loop defines a concept of using an inner loop within the body of the outer loop in the code statements. When executed, the loop gets triggered and passes to the outer loop, then the inner again. This process continues until the outer loop fulfills the condition, and this is interrupted by the break statement, which further proceeds to provide the required result.

**Syntax:**

Following is the syntax of the nested loop in Matlab with the ‘For’ loop statement:

`for m = 1:i`

for n = 1:i

[statements]
end

end

Here ‘I’ represents the number of loops you want to run in the nested loop, and the statements define the condition or numeric expression of the code. Also, the nested loop for the WHILE loop statement in Matlab:

```
while [expressions1]
while [expressions]
statements
```

end

end

### Flowchart

The following figure defines the flow chart for Nested Loop in Matlab:

### How Nested Loop Works in Matlab?

As per the above syntax, the following is an example of a nested loop in Matlab.

`a = 0;`

for m = 1:5

for n = 1:5

a = a+m+n;

end

end

But when we look at the above loop structure in Mathematics terms then, it seems that we are calculating the sum as _{m=1}∑^{5} _{n=1}∑^{5 }(m + n). This can be calculated to give the below result:

As we have taken i=5, then

`i`

^{2}(i + 1 ) = 5^{2 }* 6 = 150

This is what you get in MATLAB:

`a = 0;`

for m = 1:5

for n = 1:5

a = a + m + n; >>>>>150

end

end

### How to EXIT a Nested FOR Loop?

I know there is no smart method to exit every nested loop and run the remaining code part. Generally, we need to echo the condition each time to exit the FOR loop. You can view the following syntax:

`for m = 1:i`

for n = 1:i

[conditional statements]
if conditionforbreak

break

end

end

if conditionforbreak

break

end

end

Suppose we take the previous example to implement a break to exit the loop; then, we will get:

`a = 0;`

for m = 1:5

for n = 1:5

a = a+m+n;

conditionforbreak = a>100;

if conditionforbreak

break

end

end

if conditionforbreak

end

end

This provides the below result in Matlab:

If a = 109 or greater value than 100, then it will put a break and exit the loop. Note that ‘a’ does not repeat in a single increase, so it assures that the next repeat of ‘a’ is not 101.

### Examples of Nested Loop in Matlab

For example, we can use the nested loop to write the following code to show all the prime numbers from 1 to 50. We must create a script file and code the following nested loop statements.

`for m=2:50`

for n=2:50

if (~mod(m,n))

break;

end

end

if(m>(m/n))

fprintf(‘%d is prime \n’, m);

end

end

When you execute the above file, you will get the result below:

**Output:**

In Matlab, we can execute the code inside the iterative statements. In this code, we have nested the IF loop in the body of the statement. We can continue this as many times as required. Likewise, we can nest FOR loop inside other FOR loops, and the WHILE loop can also be executed as a nested loop to write the statements.

% to create a multiplication table; the result is saved as X.

`rows 1:10`

cols 1:10

for a = rows

for b = cols

A(a,c) = a*b;

end

end

We must remember that with any statement put in an inner FOR loop, a nested FOR loop is run once for each value of the surrounding loop. Regarding the above code script, the outside loop, i.e., the loop for a = rows’, is executed 10 times every time for each value of a. On the other hand, every time the inside loop, i.e., the loop for ‘b = cols’ modifies 10 different entries, one concerning each value of ‘b’ in the X matrix. Finally, we will get the output of a total of 100, i.e., ‘=10*10’ entries or values in table X, which is updated.

#### Indentation

Reliable use of indentation allows for creating a readable code, especially while using nested IF and FOR loops together. We can use the smart Indent feature provided by the MATLAB editor to confirm the code added is valid for the nested loop statement, like using (TEXT ->SMART INDENT). If the indentation is improper, it may hide any errors or problems.

#### Avoid or Stop a Nested Loop with A Break Statement

A BREAK statement provides logical output only inside a loop. We should also understand that the BREAK statement is used only with the innermost loop enclosing a BREAK statement. In Matlab, there are several ways of creating a FOR loop. Let us discuss a simple syntax with an example to write the loop:

`for j = 1:k % k is the number of loops that we want`

conditions; % the condition to be fulfilled for loop to execute it

end

Now let us create the loop:

`for j = 1:5`

j

end

**Output:**

### Conclusion

Hence, the Nested Loop is a control structure that helps iterate a given section of the loop statement until it meets a satisfying condition and terminates. You need to write the loops as scripts and not directly to the command window, like locating the button in the upper left corner from the NEW Script option. In this article hope you might have learned some new concepts regarding the Nested loop in MATLAB.

### Recommended Articles

This is a guide to Nested Loop in Matlab. Here we discuss the definition and how nested loop works in Matlab, flowcharts, and examples. You may also look at the following articles to learn more –