Writing the same thing, again and again, might frustrate you. This is also applicable in programming. There are several situations when a programmer needs to execute a coding program several times.

These program statements are sequentially executed, which means it will first run the first statement, then the second, and so on. Programming languages offer several control structures that grant the execution of complicated programs. This is the same in the case of “MATLAB For Loop”.

Well, Matrix Laboratory or MATLAB is a well-known programming language and multi-paradigm computer environment. It is developed by Mathworks. MATLAB connects computation, visualization, and programming in a simple, usable environment. It is all stated in mathematical equations.

Thus, in this blog, we will study MATLAB “for” loop and “while” loop. But before discussing them, we will explore some uses of MATLAB.

## Uses Of MATLAB

Table of Contents

Matlab is a mathematical computing environment. According to the Matlab website, the environment is created for subsequent uses. Some of the uses of MatLab are listed below:

Now, let’s start discussing the loops in MATLAB.

With the help of a loop statement, the programmer can execute the statements or a group of statements several times. The loops in MATLAB can be understood through the given flow diagram:

## How Do Loops In MatLab Help You?

Loops help you write the same code repeatedly and minimize your workload to execute similar code again and again.

** Suppose **a person told you to count to 500, and you have to add 2 to the previous number. You have to start from 1, then move to the next number, +2, the next number, +2, so on. This might be troublesome for you as counting to 500 with adding 2 can be an uphill task for you.

In this case, it is better to use loops in Matlab. The loops are used to perform or iterate a task number of times. This is the power of loops. This is the reason why programmers of most country sites use loops in Matlab to ease their work.

## What Are The Types Of Loops In MatLab?

Matlab offers the following kinds of loops that handle the requirement of looping a statement. Let’s check all these loops in Matlab:

### Loops in MatLab

#### While loop in matLab

It is used to repeat the number of statements or a statement when the given condition is true. It always checks the condition of the loop body before executing it.

Syntax:while <expression> <statements>end |

When an expression is taken as true, then the result of it is nonempty, and it has the nonzero element that might be real or logical numeric. Otherwise, the expression is considered to be false.

```
Input:b = 1;
while ( b < 10 )
fprintf(‘value of b: %d\n’, b);
b = b+1;
End
```

Output:Value of b: 1Value of b: 2Value of b: 3Value of b: 4Value of b: 5Value of b: 6Value of b: 7Value of b: 8Value of b: 9 |

#### For loops in MatLab

It is used to execute the sequential statement a number of specific times, and it abbreviates the program, which is used to manage the loop variable.

Syntax:for index = values <program statements> …end |

Before understanding the different kinds of For loop MatLab example, let’s have a look at the simple example of For loop.

```
for x = 2.0: -0.1: 1.5
disp(x)
end
```

**Output:**

2

1.9000

1.8000

1.7000

1.6000

1.5000

Here, the values can be of any one kind among these three values that are listed below:

#### initval:endval:

This value function can be used to increase the index variable that is incremented by 1 from initval to endval, and this will repeat the execution of the code statements until the index has greater value than endval.

```
Input:
for b = 1:10
fprintf(‘value of b: %d\n’, b);
end
```

Output:value of b: 1value of b: 2value of b: 3value of b: 4value of b: 5value of b: 6value of b: 7value of b: 8value of b: 9value of b: 10 |

#### initval:step:endval

This is used to increment the index function by the step value for each iteration, and it will decrement the value if the step is negative.

```
Input:
for b = 2.0: -0.1: 1.0
disp(b)
end
```

Output:1.900001.800001.700001.600001.500001.400001.300001.200001.100001 |

#### valArray

It is used to create an index of subsequent columns vector from a particular array, for instance: on the initial iteration, index = valArray (:, 1). The loop will execute for the n times, where n is considered to be the number of columns for valArray, which is given by numel(valArray, 1, :). The batch of input valArray involves a cell, string, struct, or cell array.

```
for b = [12,10,15,22,27]
disp(b)
end
```

Output:1210152227 |

#### Nested loops in Matlab

It is used to implement a single loop or more than one loop within other loops in Matlab. This can be done for ”while” loop or “for” loop statements.

Syntax:“For” loop for m = 1:j for n = 1:k <statements>; endEnd“While” loop while <expression1> while <expression2> <statements> endEnd |

Now, let’s check the example of MatLab Nested For loop in the below section.

```
for a = 2:30
for b = 2:30
if(~mod(a.b))
break; % if factor found, not prime
end
end
if(b > (a/b))
fprintf(‘%d is prime\n’, a);
end
End
```

Output:2 is prime3 is prime5 is prime7 is prime11 is prime13 is prime17 is prime19 is prime23 is prime29 is prime |

### MATLAB 2-D Plots Example:

**Input:**

**Output:**

### MATLAB 3-D Example:

**Input:**

**Output:**

## Which Is Better To Use For Loop Or While Loop In MatLab?

There is a certain case in which the For loop is much nicer and more compatible. When the user knows the number of iterations that will be done before the loop is started.

At the same time, the While loop is much nicer in the case when the iterations need to be determined within the loop.

Let’s compare two different codes in terms of while loop and for loop:

for k = 1:20 disp(k); end | k = 1;while k <= 20 disp(k); k = k + 1; end |

There might be some overlaps, such as executing the iterations until the specific numbers of loops or certain criterion do not reach. In such a case, the loop is most preferred as it reflects the common character of the particular loop.

So, it is easy to say that the user can use the “While” loop when he/she does not have any idea regarding the number of iterations. On the other hand, “For” loops are used when the iteration numbers are known.

## List Of Conditions In Which You Can Use While And For Loop!

- Prefer to use a For loop while you know that the loop must execute
*n*times. - Use a For loop for iterating on the columns of array.
- Practice a while loop if requesting the user’s batch of input.
- Use a while loop to read a given file within a variable.
- Practice a while loop method while the increased value is nonstandard.

## For vs While Loop MatLab: Difference You Must Know

Parameters | While Loop | For Loop |

Declaration | while ( condition) {statements; //loop body } | for(initialization; condition; iteration){//For loop body} |

Format | At the top of the loop, there is only the facility of initialization and condition checking. | Condition checking, initialization, iteration statement all can be written at the loop’s top. |

Condition | If there is no particular condition in the while loop, it gives a compiling error. | If there is no condition put up within the ‘for’ loop, the loop can easily iterate infinite times. |

Use | The ‘while’ loop is practiced only if the number of iterations is not specifically known. | The ‘for’ loop is practiced when we already know the number of iterations. |

Initialization | In the while loop, if the initialization is performed during condition checking, then initialization is completed every time the loop iterates. | Within the ‘for’ loop, once the initialization is done, it will never be repeated. |

Iteration statement | In the ‘while’ loop, the user can write the iteration statement anywhere within the loop. | In the ‘for’ loop, the iteration statement will be written at the top. Therefore, it will be executed once all statements in the loop are executed. |

## Loop Control Statements In MatLab

It is used to change the execution of the normal sequences. Whenever an execution leaves a loop, the elements of the objects will destroy the scope of that particular object. There are two different types of control statements in Matlab:

### Break statement

It is used to terminate the execution of a while or for loops in Matlab. The statements that are defined after the break statement will not get executed. Whereas, in the nested loops, it exists from a specific infinite loop in which it has occurred. The control of the statement is passed to the end of the given loop.

**Flow diagram**:

```
b = 1;
while (b < 10 )
fprintf(‘value of b: %d\n’, b);
b = b + 1;
if( b > 5)
break;
end
end
```

Output:value of b: 1value of b: 2value of b: 3value of b: 4value of b: 5 |

### Continue statement

This statement can pass the control to the upcoming or next iteration in a while or for loops in Matlab. Somehow, it also works as a break statement. Rather than forcing the termination from the loop, it moves to the next iteration of the given loop, and it skips any of the codes in between the program.

**Flow diagram:**

```
b = 1;
while b < 11 b = b + 1;
if b == 5
continue;
end
fprintf(‘value of b: %d\n’, b);
end
```

Output:value of b 1value of b: 2value of b: 3value of b: 4value of b: 6value of b: 7value of b: 8value of b: 9value of b: 10 |

## Conclusion

Matlab grants the user to use the various kinds of loops in Matlab programming that are used to handle different looping requirements that involve: while loops, for loops, and nested loops.

Besides these, it also has two different control statements that are: break statement and continue statement, which is used to control the looping of the statement in a program. Using the loops for specific repetitions statements can be a great way to shorten the final coded program.

If you have any difficulties related to assignments of Matlab, then you can avail of services for Matlab homework help and Matlab assignment help UK. We have experts team that can be accessible 24/7 with high-quality data. The services are offered at minimal prices, and we can provide you instant help that will deliver the assignments before the deadlines. So, avail of our services, and get relaxed from the complicated Matlab assignments.

## Frequently Asked Questions

### Q1. **What are loops in Matlab?**

A loop statement enables the user to execute a group of statements or a statement several times. Matlab offers different types of loops to manage looping necessities, including for loops, while loops, and nested loops.

### Q2. **What is a for loop Matlab?**

A For loop is used for repetition control structure, enabling the user to write a loop efficiently that requires to perform a specific number of times. The syntax for the ‘for’ loop in MATLAB is as: for index = values.

### Q3. **What is a while loop in Matlab?**

The while loop executes the program statement(s) repeatedly as long as the condition remains true. A condition is true till the output is nonempty and includes all nonzero components (real numeric or logical). Otherwise, the condition is false.