Loops are one of the most powerful tools at your disposal as a programmer. Loops allow you to execute a statement or group of statements multiple times. These can be used for a variety of purposes, including:

  • Repeating a task until some condition is met
  • Performing an operation on every element in an array
  • Building up an array by adding elements one by one
  • Repeating an operation until you get the result you want

Serious About Success? Don't Settle for Less

Learn 30+ Skills With Our Data Scientist ProgramExplore Program
Serious About Success? Don't Settle for Less

What are Matlab Loops and Conditional Statements?

Loops are essential to programming, and MATLAB provides many looping options. In this article, we will explore the different types of loops that MATLAB provides and the use of midpoint break loops.

Loops are used to repeat a set of commands until a condition is met or until a certain number of iterations have been completed. 

MATLAB provides different types of loops to handle looping requirements, including: 

  • While loops.
  • For loops.
  • Nested loops. 

If we are trying to declare or write our loops, we need to ensure that the loops are written as scripts and not directly in the Command Window.

Different Types of Matlab Loops (With Examples)

MATLAB has three types of loops: for, while, and nested loops. Each of these loops has a different syntax and use case. Here's an introduction to each type of loop, along with flowcharts and detailed explanations of each flowchart segment.

While Loop

A while loop is a programming language control structure. It executes a statement or group of statements repeatedly as long as a specified condition is proper.

Syntax:

while condition

    % commands

End

condition is a logical expression that must be true to continue the loop.

The commands inside the loop are executed until the condition is false.

Flowchart:

The flowchart for a while loop is as follows:

┌─────────────────┐

│  (Initialize)    │

└─────────────────┘

          │

      (Condition)

          │

      ┌────┴────┐

      │ Commands │

      └─────────┘

          │

      (Update)

          │

        Loop

Explanation:

  1. Initialize: Any necessary variables are initialized before entering the loop.
  2. Condition: The loop continues while the condition is true.
  3. Commands: The commands inside the loop are executed.
  4. Update: Any necessary updates are made to the loop variables.
  5. Loop: The loop returns to step 2 and repeats until the condition is false.

Example:

num = 20;

% while loop execution 

while( a < 30 )

   fprintf('value of a: %d\n', a);

   a = a + 1;

end

value of num: 20

value of num: 21

value of num: 22

value of num: 23

value of num: 24

value of num: 25

value of num: 26

value of num: 27

value of num: 28

value of num: 29

For Loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

It's similar to the while loop, but it has two significant differences:

  • You can say how many times the loop should repeat instead of having the loop continue until some condition is true.
  • The condition at the end of the loop is checked before each iteration instead of after each iteration with while loops.

Syntax:

for i = start:increment:end

% commands

end

i is a loop variable that takes on values from start to end with an increment of increment.

The commands inside the loop are executed for each value of i.

Flowchart:

The flowchart for a for loop is as follows:

┌───────────────────┐

│    Initialize     │

└───────────────────┘

           │

      (Condition)

           │

      ┌────┴────┐

      │ Commands │

      └─────────┘

           │

      (Increment)

           │

         Loop

Explanation:

  1. Initialize: The loop variable i is initialized to start.
  2. Condition: The loop continues while i is less than or equal to the end.
  3. Commands: The commands inside the loop are executed.
  4. Increment: The loop variable i is incremented by increment.
  5. Loop: The loop returns to step 2 and repeats until the condition is false.

Example:

for num = 0:10 

   fprintf('value of a: %d\n', a);

end

value of num: 0

value of num: 1

value of num: 2

value of num: 3

value of num: 4

value of num: 5

value of num: 6

value of num: 7

value of num: 8

value of num: 9

value of num: 10 

Serious About Success? Don't Settle for Less

Learn 30+ Skills With Our Data Scientist ProgramExplore Program
Serious About Success? Don't Settle for Less

The Nested Loops

In MATLAB, it is possible to use one loop inside another loop. It can be helpful, for example, when you want to run a certain number of iterations of an inner loop and then stop the outer loop once it reaches a specific condition.

The following examples illustrate this concept:

Syntax:

for i = start1:increment1:end1

    for j = start2:increment2:end2

        % commands

    end

end

i is the outer loop variable, and j is the inner loop variable.

The commands inside the inner loop are executed for each value of j, and the inner loop is repeated for each value of i.

Flowchart:

The flowchart for a nested loop is as follows:

┌───────────────────┐

│    Initialize i    │

└───────────────────┘

           │

      (Condition i)

           │

┌───────────────────┐

│    Initialize j    │

└───────────────────┘

           │

      (Condition j)

           │

      ┌────┴────┐

      │ Commands │

      └─────────┘

           │

      (Update j)

           │

         Loop j

           │

      (Update i)

           │

         Loop i

Explanation:

  1. The outer loop variable i is initialized.
  2. The condition for the outer loop is evaluated.
  3. The inner loop variable j is initialized.
  4. The condition for the inner loop is evaluated.
  5. The commands inside the inner loop are executed.
  6. The inner loop variable j is updated.
  7. The inner loop is repeated until the condition is false.
  8. The outer loop variable i is updated.
  9. The outer loop is repeated until the condition is false.

Example:

for i = 2:12

   for j = 2:12

      if(~mod(i,j)) 

         break; % if factor found, not prime

      end 

   end

   if(j > (i/j))

      fprintf('%d is prime\n', i);

   end

end

2 is prime

3 is prime

5 is prime

7 is prime

11 is prime

Loop Control Statements (With Examples)

The break and continue, you can use commands to create a third type of loop, known as a midpoint break loop. A midpoint break loop is helpful for situations where you must execute the controls in the loop at least once but where the decision to exit the loop is based on some criterion.

A midpoint break loop has two parts: inner and outer sections. The inner section contains repeated statements until some criterion is met. When this condition is met, execution jumps to the first statement after the inner section and continues with the next iteration of the outer section.

Break Statement

The break statement terminates the execution of a for or while loop and transfers control to the statement that appears after the end of the loop.

In a for loop, the break transfers control to the first statement immediately following the end of the loop body.

In a while loop, the break transfers control to the first statement immediately following the end of the loop body.

num = 20; 

% while loop execution 

while (num < 20 ) 

fprintf('value of a: %d\n', num); 

num = num+1; 

if( num > 15) 

% terminate the loop using a break statement 

break; 

end 

end 

value of num: 10 

value of num: 11 

value of num: 12 

value of num: 13 

value of num: 14 

value of num: 15

Become the Highest Paid Data Science Expert

With Our Best-in-class Data Science ProgramExplore Now
Become the Highest Paid Data Science Expert

Continue Statement

The continue statement is a MATLAB construct that allows you to stop the execution of a loop, and then force the next iteration of the loop to take place.

When you use a for or while loop in MATLAB, there will be code between the opening and closing curly braces. This code is called an "interloop". When you use the continue statement, it will skip over any code in between the two curly braces and jump straight to the next iteration of the loop.

Example: 

num = 10; 

%while loop execution 

while num < 20 

if num == 15 

% skip the iteration 

num = num + 1; 

continue; 

end 

fprintf('value of num: %d\n', num); 

num = num + 1; 

end

value of num: 10 

value of num: 11 

value of num: 12 

value of num: 13 

value of num: 14 

value of num: 16 

value of num: 17 

value of num: 18 

value of num: 19

FAQs

1. What are loops in MATLAB?

Loops and conditional statements are powerful tools for writing programs. These constructs provide a way to execute code repeatedly or conditionally and can be used to control the flow of a program. 

2. What are the three types of loops?

Following are the three types of loops:

  1. For loop.
  2. While loop.
  3. Nested loop.

3. Why is a loop used in MATLAB?

You can write programs more efficiently with loops and conditional statements. These constructs can control a program by repeating or conditionally executing the code. 

4. How do you use “for” loops?

For Loops: A for loop repeats a code block until a specific condition is met. It takes the following form:

for index = initval:endval | initval:step:endval | valArray

    <program statements>

            …

end

5. How do you run a loop in MATLAB?

Loops are an essential tool in any programming language. They allow you to repeat a block of code a specific number of times or as long as a condition remains true.

There are two types of loops: 

  • For statements, loop a specific number of times, and keep track of each iteration with an incrementing index variable. The variable is automatically incremented by one after each iteration.
  • While statements loop as long as a condition remains true.

Conclusion

If you're looking to become a data scientist, there's no better way to start than learning MATLAB.

Data scientists use MATLAB to solve complex problems and make sense of the data they collect. It's one of the industry's most sought-after programming languages and will only get more popular as time goes on.

Simplilearn's Caltech Post Graduate Program in Data Science will help you master MATLAB and other programming languages like Python and R. You'll also learn how to apply data science techniques to solve real-world problems.

The course covers various topics in depth and has a lot of practical components for getting you job-ready from day one.

Data Science & Business Analytics Courses Duration and Fees

Data Science & Business Analytics programs typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Post Graduate Program in Data Analytics

Cohort Starts: 7 Nov, 2024

8 months$ 3,500
Professional Certificate in Data Analytics and Generative AI

Cohort Starts: 7 Nov, 2024

5 months$ 4,000
Caltech Post Graduate Program in Data Science

Cohort Starts: 11 Nov, 2024

11 months$ 4,000
Professional Certificate Program in Data Engineering

Cohort Starts: 13 Nov, 2024

32 weeks$ 3,850
Post Graduate Program in Data Science

Cohort Starts: 18 Nov, 2024

11 months$ 3,800
Applied AI & Data Science14 weeks$ 2,624
Data Scientist11 months$ 1,449
Data Analyst11 months$ 1,449