A Complete Guide on Loops in Matlab With Relevant Examples

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 execute the first statement, then the second, and so on. Programming languages offer several control structures that grant the execution of complicated programs. 

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:

Loop Architecture

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” loops 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.

Example:

Input:

b = 1;

while ( b < 10 )

fprintf(‘value of b: %d\n’, b);

b = b+1;

End

Output:

Value of b: 1

Value of b: 2

Value of b: 3

Value of b: 4

Value of b: 5

Value of b: 6

Value of b: 7

Value of b: 8

Value of b: 9

  • “For” loops in Matlab
READ  A Definitive Guide on Types of Error in Statistics

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

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

  1. 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.

Example:

Input:

for b = 1:10 

   fprintf(‘value of b: %d\n’, b);

end

Output:

value of b: 1

value of b: 2

value of b: 3

value of b: 4

value of b: 5

value of b: 6

value of b: 7

value of b: 8

value of b: 9

value of b: 10

  1. 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.

Example:

Input:

for b = 2.0: -0.1: 1.0

   disp(b)

end

Output:

2

1.90000

1.80000

1.70000

1.60000

1.50000

1.40000

1.30000

1.20000

1.10000

1

  1. 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.

Example:

Input:

for b = [12,10,15,22,27]

   disp(b)

end

Output:

12

10

15

22

27

  • “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>;

   end

End

“While” loop

while <expression1>

   while <expression2>

      <statements>

   end

End

Example:

Input:

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 prime

3 is prime

5 is prime

7 is prime

11 is prime

13 is prime

17 is prime

19 is prime

23 is prime

29 is prime

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. 

READ  How to Select Dissertation Topics in Accounting And Finance

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);endk = 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.

What is the common difference between While and For loops in Matlab?

ParametersWhile LoopFor Loop
Declaration while ( condition) {statements; //loop body }for(initialization; condition; iteration){//For loop body}
FormatAt 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.
ConditionIf 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.
UseThe ‘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.
InitializationIn 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 statementIn 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
READ  What is Accounting And Why Accounting is Important For You?

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

MATLAB break statement

Example:

Input:

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: 1

value of b: 2

value of b: 3

value of b: 4

value 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:

MATLAB continue statement

Example:

Input:

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 1

value of b: 2

value of b: 3

value of b: 4

value of b: 6

value of b: 7

value of b: 8

value of b: 9

value 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 help with MATLAB homework. 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

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.

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.

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.

Leave a Comment