Loops in MATLAB: A Quick Tutorial With Practical Examples

Loops In MatLab

In real life, many times, we have to perform several tasks again and again until a specific task is reached. That’s why Matlab has a repetitive function called loops. There are a lot of loops in Matlab, and for almost every loop in Matlab, we will see how to code it. Many individuals do not know about these loops. So before we start to discuss these loops, let’s understand the main purpose of loops in programming.

With the help of loops, you can run the block statements many times. So the statement was performed successfully: the first statement is executed, the second one, and so on.  In MATLAB, you find the various types of loops that use for different purposes. All these loops can fulfill the requirements of while loops, for-loop, and nested loops. In this blog, you can learn about loops in Matlab in detail.

What is Matlab?

Plotting functions and data, matrix manipulations, algorithm implementation, user interface design, and connecting with programs written in other languages are all possible with the help of Matlab. When it comes to writing codes, MATLAB uses a command-line interface that is almost a character-based one. These character-based codes are sometimes referred to as M-codes. Following the commands provided in these codes, the software can be used for plotting and manipulating data.

Specific services include
  • Computation and mathematics.
  • Development of algorithms.
  • Simulation, modeling, and prototyping.
  • Analyzing, exploring, and visualizing data.
  • Graphics for scientific and engineering purposes.
  • Development of applications, including graphical user interfaces.

Types of loops in Matlab

A loop is a set of instructions that is repeated until a given condition is met in computer science. Loops are used by programmers to repeat the task using values, add numbers, repeat functions, etc. The majority of modern programming languages support loops, though their implementations. But their syntax may differ. While loops, nested loops and for loops are three of the most common types of loops.

loops in matlab
While loops

While loops work with simple phenomena. They execute the statement continuously until a condition is met. The while loop has the following syntax:-

While <expression>

<statement>

End

The while loop repeatedly executes the program statement until the expression becomes false. The condition becomes true if the results contain a non-zero element or if the result is non-empty. Otherwise, the condition becomes false.

For Example:

x = 25;
% execution of while loop  
while( x < 30 )
   fprintf('The value of x: %d\n', x);
   x = x + 1;
end

Output:

The value of x: 25

The value of x: 26

The value of x: 27

The value of x: 28

The value of x: 29

For loop

In the Matlab programming language, the for loop is the best. It provides repetition control. By using it, you can write a loop that executes the condition any number of times. The syntax of a for loop in MATLAB

for index = values 

<programming statements>

End

There are several types of value: 

initval:endval- In this case, the index variable from initval to endval must be multiplied by one. The statement continues to execute until the index is greater than the endval.

Initval:step:endval- On each repetition, the index is increased by one. In the case of negative values, it decreases. 

valArray- From subsequent columns of the array, the program creates a column vector index. valArray on each iteration. 

For Example:

for x = 5:10
   fprintf('The value of x: %d\n', x);
end

Output:

The value of x: 5

The value of x: 6

The value of x: 7

The value of x: 8

The value of x: 9

The value of x: 10

The Nested Loop

Matlab also allows you to use a loop inside another loop. In MATLAB, there are two types of nested loops. The first one is a nested for loop, and the second one is a nested while loop.

The syntax for the for loop in MATLAB is as follows.

In MATLAB, a nested while loop statement has the following syntax:

while <expression1>

while <expression2>

<statement>

End

End

For Example:

for p = 2:10
   for q = 2:10
      if(~mod(p,q)) 
         break; % if the factor is found, not prime
      end 
   end
   if(q > (p/q))
      fprintf('%d is prime\n', p);
   end
end

Output:

2 is prime

3 is prime

5 is prime

7 is prime

Difference Between For Loop and While Loop

Loops are a powerful and fundamental feature of almost any computer programming language. Loops allow the programmer to tell a computer to repeat a block of code a particular number of times. There are two basic types of loops in most programming languages: the while loop and the for loop. 

While loops are easier to understand, for loops are generally more helpful in practice. The majority of programming examples of loops only use a single statement inside the loop to control the iteration, but if the loop is only run once. In this section, we will explain the difference between a for loop and a while loop.

  • The number of iterations to be performed in a for loop is already specified, whereas, in a while loop, the number of iterations is unknown.
  • While a for loop only has one condition, a while loop can have many commands that are executed simultaneously.
  • While initialization of command is only required once in a for loop, it is required each time the command is iterated in a while loop.
  • In a for loop, if the condition is missing, the loop repeats indefinitely, whereas in a while loop, the lack of the condition results in an error.
  • While for loop can only be used when the number of iterations is known, while loop can only be used when the number of iterations is unknown.

Are there any Loop Control Statements in Matlab?

A control statement is a set of conditions that permits the loop to continue running until a certain condition is satisfied. It also controls the loop’s syntax. In a while loop, for example, the comparative value is defined before the loop begins. In contrast, the value conditions are specified in the for statement during the initialization of a for a loop.

The loop control statement controls the execution of a loop or changes the execution from the normal sequence of commands. There are two specific loop control statements in MATLAB: break and continue. These statements are used in almost every language.

Break Statement

When the break command is used, the for or while loop will be terminated. The statements written after the break statement in the loop are skipped / not executed. If nested loops are encountered, the break will only exit from the loop in which it is used. At the end of the loop, control goes to the statement that follows.

For Example:

p = 25;
% execution of while loop  
while (p < 30 )
   fprintf('The value of p: %d\n', p);
   p = p + 2;
      if( p > 35)
         %  the terminate of the loop using break statement 
         break;
      end 
end

Output:

The value of p: 25

The value of p: 27

The value of p: 29

Continue Statement

The continue command controls the next iteration of the loop. It is similar to the break statement. Instead of forcing termination, ‘continue’ skips all code between iterations and forces the next one to be executed.

For Example:

p = 9;
%the execution of the while loop 
while p < 15
   p = p + 1; 
   if p == 11
      % skip the iteration 
      continue;
   end 
fprintf('The value of p: %d\n', p);
end

Output:

The value of p: 10

The value of p: 12

The value of p: 13

The value of p: 14

The value of p: 15

Conclusion

In this blog, we have given different types of loops in Matlab to handle repetitive requirements, including for loops, while loops, and nested loops. And also mention detailed control information to control the execution of these loops.

If you are a programming student facing difficulties in completing your assignment, don’t get stressed. Our experts offer Matlab Assignment Help to students at the lowest price.

Frequently Asked Questions

What are loops in Matlab?

Loop Type & Description

If loop: when a given condition is true, the loop repeats a given statement or group of statements. It tests the condition before executing the loop body.

For loops, execute a sequence of statements multiple times. They also abbreviate the code that manages loop variables.

How do you stop a loop in MATLAB?

To stop the execution of a MATLAB® command, press Ctrl+C or Ctrl+Break. On Apple Macintosh platforms, you also can use Command+.