Categories

## Break in MATLAB

Break-in MATLAB is the command that is used to terminate the execution of any FOR or WHILE loop before the looping condition expires. Post break statements within the immediately associated loop do not get executed. The scope of the execution of the break statement is within its immediate ‘For’ or ‘While’ loop.

In real-time, let us consider a system which is running based on the temperature of its environment/surrounding. The working of the system is regulated based on the variation in the surrounding temperature. But in case the temperature reaches the level which is dangerous for the system, the execution of the program should immediately be stopped. In such a case in the program designing, a break statement must be used.

The keyword ‘Break’ is used to define the break statement.

`break`

## How to Use Break in MATLAB?

Below are some of the uses in MATLAB:

## 1. Use of Break within a single loop

Break command is used to take control out of the loop without executing the instruction designed after the break statement within the scope of the loop.

## Example:

The below code snippet is written to demonstrate the application of the break statement with a single loop. The code is written to run a while loop to go through each value of the matrix ‘a’. The break instruction will be called when any number in the matrix ‘a’ is equal to 25. When there is value equals to 25, the break statement will be executed and the disp() commands after a break will not get executed.

### Code:

``````% Program to break the flow of Execution
% randi() is used to generate numbers between 0 to 30 positioned in 4X4 matrix
a = randi(30,4,4)
k = 1;
while k
disp('Control has entered into the loop')
if a(k) ==25
disp('program encounters the number 25')
disp(['at index no.:',num2str(k)])
disp('Hence control in inside the If condition')
disp('Break state will be executed now')
% terminate the loop using break statement
break
disp('This statement is designed immediate after the break statement')
end
disp('This statement is designed outside of the if condition within the loop')
k = k+1;
end
disp('This statement is designed after the break statement outside of the loop').``````

### Output:

The matrix ‘a’ of 4X4 size is generated from the randi() function. If the condition is hit for 4th position and control has come out of the loop.

## 2. Use of Break with a nested loop

When the break statement is called from the nested loop, the control comes out from the immediate inner loop, which has the break statement.

## Example 1:

The below code snippet is written to illustrate the behavior of the break statement used for an inner loop as well as for the outer loop.

The values from matrix ‘i’ have created the outer loop whereas the values from matrix ‘j’ have created the inner loop.

### Code:

``````% Program to break the flow of Execution
flag=0;
%Beginning of outer loop
for i=1:10
disp(['Value of i: ',num2str(i)])
%Beginning of inner loop
for j=1:5
disp(['Value of j: ',num2str(j)])
disp('Control is in inner loop')
if(j==3)
disp('Break statement from inner loop will be executed')
% Break statement to come out of the inner loop
break
end
disp('Statement is designed outside of inner if condition')
flag=1;
end
disp('Control is outside of the inner loop')
% Break statement to come out of the outer loop
if(flag==1)
disp('Break statement from outer loop will be executed')
break
end
disp('Statement is designed outside of outer if condition')
end
disp('Control is outside of the outer loop')``````

### Output:

Break statement from the inner loop is executed when the inner if the condition results in a true value. The control came out of the inner loop but the outer loop is continued unaffected. Control in the outer loop is continued until the if condition present in the outer loop is not resulted in true.

The application of Break also helps to improve the coding quality. It optimizes the coding execution time hence improve the performance of the application.

## Example 2:

The below code snippets are written to read the first negative number that is present in the matrix ‘a’. Case 1 is written without using a break statement whereas case 2 has the code snippet which is developed using a break statement.

### Case 1:

``````% program to terminate the execution on finding negative input
a = randn(4)
k = 1;
flag=0;
negnum=0.0;
pos=0;
%Beginning of while loop
while k < numel(a)
if a(k) < 0
flag=1;
negnum=a(k);
pos=k;
end
k = k + 1;
end
if flag ==1
disp(['negative number :', num2str(negnum), ',found at index: ', num2str(pos),',hence the program terminated'])
else
disp('There is no negative number present in the matrix')
end``````

### Output:

In this case, the loop is executed until the looping condition is in action. The control still revolves within the loop even after a negative number is found. Once the loop will be over, then it displays the result. This code snippet includes the number of variables, more lines of code. In the case of huge data, the execution shall take a long time and hence the performance of the program will be significantly slower.

### Case 2:

``````% program to terminate the execution on finding negative input
a = randn(4)
k = 1;
%Beginning of the while loop
while k < numel(a)
%Use of break statement to fetch the result fast
if a(k) < 0
break
end
k = k + 1;
end
if a(k) < 0
disp(['negative number :', num2str(a(k)), ',found at index: ', num2str(k),',hence the program terminated'])
else
disp('There is no negative number present in the matrix')
end``````

### Output

In this case, the control comes out of the loop once the first negative number is fetched. Once the desired result is achieved, the additional execution does not take place. Hence execution is fast and performance is improved. It involves fewer variables or lines of code which has reduced the complexity of the program.

Break and return, both are used to redirect the flow of execution. The difference exists as a return statement returns the control to parent calling function where is break statement takes the control out from its immediate loop and continues the same function execution.

Categories

## Switch Statement?

In this article, we will see the Switch Statement in Matlab. Before that let see what is Matlab.
The name MATLAB is a short form of Matrix Laboratory. MATLAB is one of the best programming languages for scientists and technical computing. It contains an environment for computation, data visualization, and logic programming. It contains inbuilt editing and error debugging tools, and it supports the idea of OOP. These factors make MATLAB great use and a preferred tool for academic teaching and research.

We are familiar with the basic concepts of MATLAB. We know MATLAB data types, basic operations in MATLAB and loops. In this article, we shall focus on the switch. Switch statements are another control flow logic in MATLAB which is used extensively. Let’s learn about the switch.

In general, we can create multiple alternative selection logic using the if-else, If statements. However, that method makes the code long and also hard to read and debug, we have another good way or let’s say a better way to make those selections. A switch statement helps us choose one among a number of options using code that is easier to read, as said and less time-consuming to typing and editing. The results from both these methods are essentially the same, but the method of implementation varies.

## Syntax of Switch Statement in Matlab

In this section, we provide the standard syntax of the switch statements and provide step by step explanation.

``````switch switch_condition
case case_condition
statements_if_true
case case_condition
statements_if_true
...
Otherwise_condition
Statements_if_true
end``````

## Explanation

The first two lines “switch_ condition, case_ condition, end” performs an evaluation of an expression and then make a choice for executing one of several statements. Each of such choices is called a case.

The switch block performs the test on each case until one of the case expressions is found to be true. A case is termed as true when if satisfy:

• In the case of numbers, its case_ condition is equal to the switch_ condition.
• In the case of character data types, its strcmp(case_ condition, switch_ condition) is equal to 1.
• In the case of objects which support the equation like function, case_ condition should be equal to switch_ condition.
• In the case of cell array type data structure minimum, one of the given elements of the cell array will match with the given switch_ condition.
• When a case condition is found to be true then MATLAB executes that statement and after execution come out of the switch
• For it to work properly, the evaluated switch_ condition should be scalar data type or character vector data type.
• The otherwise block is optional and is executed when no case is found to be true.

## Flow Diagram in Switch Statement in Matlab

In this section, we provide the flow diagram for the above syntax for easy understanding. If you simply read each block of statements, you would be able to understand the working of a switch. That’s the power of flow diagram and that is why it is taught to every beginner programmer. It helps you frame your logic and design the error-free code before actually writing it.

## How Switch Statement Works in MATLAB?

We understood the technical details of the switch statement. Lest focus a little more on its working now.

A switch block as mentioned previously, conditionally executes one set of statements based on criteria from several choices. Each of these choices is covered by a case statement.

When we see examples in the section below, the construct of the switch statement as well as its function will be clearer. A couple of things that we can notice is that the switch statement in MATLAB may be a little different than the other programming language. For example, The MATLAB switch construct is different in some respects from the C programming language construct of the switch. The C switch construct allows for execution to go through many case groups before its execution halts. In C, we can use break statements to control the execution. The idea, however, is different in MATLAB, where switch construct executes one case group only and hence it does not need break statements.

## Examples of Switch Statement in Matlab

Let us see some of the examples of the switch statement in Matlab.

## Example 1:

This example does a very simple job. The core idea is to pass through a switch statement and print message based on some condition. We create a basic logic of matching the number and providing an output based on the number.

``````N = input('Enter a number of your choice: ');
switch N
case -2
disp('negative one selected')
case 0
disp('zero selected')
case 2
disp('positive one selected')
otherwise
disp('Some other value')
end``````

### Output:

At the command prompt, enter the number -2.

negative two

Repeat the code and enter the number 5.

Some other value

## Example 2:

In this example of Switch Statement in Matlab, based on the grade obtained, we classify the distinction.

``````Enter_grade = 'A';
case 'A'
fprintf('Excellent performance!\n' );
case 'B'
fprintf('Well done performance\n' );
case 'C'
fprintf('Very Good performance\n' );
case 'D'
fprintf('You passed.. Congratulations\n' );
case 'F'
fprintf('Better luck next time\n' );
otherwise
fprintf('Invalid grade. Please enter correct value\n' );
end``````

### Output:

After running, it will display Excellent Performance as the chosen grade in the first line of code is A. Replace that A with B and run again, you will get the output as Well-done Performance. So, based on the grade selected, the distinction comes, and all of this could be done is about 10 lines of code. Imagine doing the same user if-else logic and the code will be much longer and will contain many additional conditional statements.

Categories

## Nested Loop in Matlab

Nested Loop is a compound statement in Matlab where we can place a loop inside the body of another loop which nested form of conditional statements. As you have known that, Matlab allows you to combine some compound statements like IF, 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 another type 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 to use an inner loop within the body of the outer loop in the code statements. When executed the loop gets triggered 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 ‘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 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 term then, it seems that we are calculating the sum as m=15 n=1(m + n). This can be calculated to give the below result:

As we have taken i=5, then

``i2(i + 1 ) = 52 * 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?

Inappropriately, there is no smart method in my knowledge 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 if we take the previous example to implement 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 to use the nested loop we can write the following code to show all the prime numbers from 1 to 50. We need to 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:

Here, 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 in the form of a nested loop to write the statements.

% to create a multiplication table and 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 need to remember that along with any statement that is put in an inner FOR loop, a nested FOR loop is run once for each value of the surrounding loop. Talking about 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 with respect to each value of ‘b’ in the X matrix. Finally, we will get the output of total 100 i.e. ‘=10*10’ entries or values in table X which is updated.

## Indentation

Reliable use of indentation allows creating a readable code especially while using nested IF and FOR loops together. We can use the smart Indent feature provided by MATLAB editor so that we can confirm the code added is valid for the nested loop statement, like using (TEXT ->SMART INDENT). If the indentation is not proper then, 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 to know the BREAK statement is used only with the innermost loop that encloses 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 wantconditions;  % the condition to be fulfilled for loop to execute itend`

Now let us create the loop:

`for j = 1:5jend`

Categories

## do while loop in Matlab

Basically there is no do while loop in Matlab like c programming, cpp programming, and other programming languages. But instead of using do while loop works powerfully in Matlab. In Matlab, mostly two loops are used to do operations. If we are sure about how many times we need to perform a particular task then for loop is used. And if we are not sure about how many times we want to perform a particular task then while loop is used. Inside the loop, we can write condition and repetition statements of particular programs and increment/decrement of variables.

The syntax used to write while loop in the program is ‘while’ command and at the end, we need to write ‘end’ command to stop the loop.

## How do while loop works in Matlab?

To write while loop in Matlab always we need to consider three parameters.

• The first condition limits the loop at the time of execution.
• Second parameter statements mean what is actually expected output.
• Th third parameter is the incrementing loop variable. If we missed the increment line then the loop will execute infinite times.

### Syntax:

``````while(condition)
Statement1
Statement2
.
.
Statement n
Increment loop variable syntax``````

## Examples of do while loop in Matlab

Given below are the examples of do while loop in Matlab:

## Example 1:

In this example let us consider one variable a. The initial value assigned to a is 2. After applying condition ( a < = 5) along with while loop, loop will execute for values 2, 3, 4, 5. And here statement just displays the value of a. Therefore it will display output as 2, 3, 4, 5.

### Code:

``````a = 2
while(a <= 5)
disp(a)
a = a + 1;
end``````

## Example 2:

The second example is a square function. In this example, we are going to find out the square of values till 5. Here var is the variable name. The value assigned to var is 1 so that var will vary from 1 to 5.

### Code:

``````var = 1
while(var <=5)
op=var*var;
disp(op)
var = var + 1;
end``````

## Example 3:

In this example there are two different operations, one is even numbers and the second is odd numbers. To find out even and odd numbers we have used two different while loops.

### Code:

``````var = 0
disp('even numbers')
while(var <= 10)
disp(var)
var = var + 2;
end
var = 1
disp('odd numbers')
while(var <= 10)
disp( var )
var = var + 2 ;
end``````

## Example 4:

In previous examples, we start the problem from the origin, but by using a while loop we can change the range of problems. In this example, we consider numbers from 41 to 65. Here we have used two variables. Var is used for start and end at is used for the end of the range.

### Code:

``````% even numbers between 41 to 65
var = 40
endat = 65
disp('even numbers')
while(var <= 65)
disp( var )
var = var + 2;
end
var = 41
disp('odd numbers')
while(var <= endat)
disp( var )
var = var + 2 ;
end``````

## Example 5:

By using a while loop we can create various number series and applications. In this example, we created a series of numbers by considering output previous iterations.

### Code:

``````% addition of previous numbers
var = 0
endat= 10
op = 0
disp('number series ')
while(var <= endat)
%disp(var);
op = op + var
var = var + 1 ;
end``````

Categories

## While loop in MATLAB

MATLAB is a scientific programming language that is used a lot for research and academic purposes. A lot of industries are also using it, but universities and research organizations are the main customers of this proprietary software tool. MATLAB is developed by MathWorks and in order to use it, one must purchase a license. For students and beginners, however, it does come with a limited-time trial version.

It is so popular that it is used by colleges and universities across the world to teach scientific computation and engineering such as signal processing, control system, advanced mathematics, and many other subjects. Today, even after the easy availability of open-source software such as R and Python for similar work, it is still popular and used extensively.

In this article, we provide basic building blocks of MATLAB and specifically focus on a while loop. If you are familiar with other programming languages then you must be aware of loops such as for loop, if loop, while loop, etc. We shall talk about the same in the context of MATLAB. And, if you are completely new to programming then as well you need not worry as the discussions in this article is at absolute beginner level and you are not required to have a programming background. But, it is expected that you know the basic data types in MATLAB.

### Syntax:

In this section, we shall provide syntax of a while loop and then subsequently explain the same in step by step method.

``````while expression
statements
end``````

## Explanation:

1. While is the keyword for while loop.
2. An expression is a condition that needs to be true for the while loop to work.
3. Statements are the actions that would be executed if the condition or expression is true.
4. The end is the keyword which suggested the closure of the loop.

To better understand the syntax, let’s take an example.

## Example:

``````a = 10;
% while loop execution example
while( a < 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
end``````

### Explanation of the Example

1. We define a variable to be equal to 10
2. A line starting with % is the comment in MATLAB, so we can ignore the same.
3. While loop starts and the condition is less than 20. What it means is that the while loop will run till the value of a is less than 20. Note that currently, the value of a is 10.
4. Next line prints the current value of a and after that, the next line is executed
5. The line a=a+1, adds 1 to a and then the while condition is again checked. Now the value of a is 11 which is still less than 20 so the loop runs again.
6. Finally, the loop runs until a attains the value 19 and after that, it stops.

The detailed output will be shown in the example section.

## Flow diagram

Let’s understand the flow diagram of a while loop for better clarity.

The flow diagram above is quite simple and self-explanatory. It is the same as the steps described above in the syntax section. When the Boolean condition is true the statements are executed otherwise it does nothing and loop execution stops.

## How while Loop Works in MATLAB?

The working of the while loop is quite clear from the flow diagram above. A step by step explanation of syntax is also provided in the syntax section. In this section, we shall explain the same ideas in more detail.

A while loop has mainly three parts that need to be understood.

1. There has to be some Boolean condition that would be evaluated by the loop.
2. There needs to have some action for that Boolean condition. i.e. what happens when the condition is true and what happens when the condition is false.
3. The control of the loop moves according to the nature of the condition i.e either it computes something, or it stops working.

Based on the condition provided, a while loop can run for a finite number of times producing finite output or it can go for as long as possible unless stopped manually.

An infinite loop may look like below:

``````N=1;
While N < 5
N = N-1
end``````

You may note here that as the value of N is decreasing in each iteration, it will always satisfy the condition and hence will continue working infinitely. Is not it simple and yet so powerful?

## Examples of while loop in Matlab

Let’s talk about a few examples to understand further.

## Example 1 – This is the same example as above

``````a = 10;
% while loop execution example
while( a < 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
end``````

### Output:

```Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19```

## Example 2:

``````i = 1;
s = 0;
% while loop execution example
while( i < 3 )
fprintf('intermediate sum: %d\n', s);
s = s + i;
i = i + 1;
end``````

### Output:

```intermediate sum = 0
intermediate sum = 1```

## Example 3:

``````i = 1;
while (i < 3)
i
i = i + 1;
end``````

```i = 1
i = 2```
Categories

## For Loop in Matlab

MATLAB provides its user with a basket of functions, in this article we will understand a powerful element called ‘For loop’. For loop is a conditional iterative statement used in programming languages. It is used to check for desired conditions and then executes a block of code repeatedly. The block of code is implemented as long as those defined conditions are met. An explicit loop counter is used to distinguish ‘for loop’ from other looping statements. This is also referred to as the loop variable, this allows the loop body to know the sequencing of every iteration. In this topic, we are going to learn about For Loop in Matlab.

### Syntax of For Loop:

``````for index = value/values
statement
end``````

Now let us understand ‘for loop’ in detail.

## Examples of For Loop in Matlab

For index = It will include values, single or multiple statements, and end

This function will run a defined set of statements in the loop for the number of times specified in the condition

Values can have a number of forms e.g:

• firstVal: lastVal: it will gradually increase the index by 1 from firstval till lastval, it will run the set of statements till firstVal is greater than the lastVal
• firstVal: step : lastVal: it will gradually increase the index by defined “step” value or it will decrease the value by “step” for negative values
• valArray: For each iteration, it will generate a column vector from columns of the array for valArray

Now let us use ‘for loop’ in some examples:

## Decrement Values

It will decrement the values by the defined interval.

### Code:

``````for a = 2.0 : -0.5 : 0.0
disp(a)
end``````

Here, our output will be decremented by ‘0.5’

### Output:

Let’s take a different decrement interval

### Code:

``````for a = 3.0 : -1.0 : 0.0
disp(a)
end``````

Here is the output that we will get, as we can notice, the values are decremented by 1:

## Increment Values

It will increment the values by the defined interval.

### Code:

``````for a = 6.0 : 1.0 : 9.0
disp(a)
end``````

Here is the output that we will get, as we can notice, the values are incremented by 1:

Let’s take a different decrement interval:

### Code:

``````for a = 4.0 : 2.0 : 9.0
disp(a)
end``````

Here is the output that we will get, as we can see, the values are incremented by 2:

## Specified Values

It will execute statements for specified values

### Code:

``````for a = [1 3 8 7] disp(a)
end``````

This is how our output will look like:

### Output:

As we can notice, the values are simply printed.

## Use of Repeat Statement for every Matrix Column

Here the eye is a 2X3 Identity matrix

### Code:

``````for I = eye (2,3)
disp('Current value:')
disp(I)
end``````

This is how our output will look like:

## Use of BREAK Statement

To exit the ‘for loop’ we can use the break statement. Without break, the following example will print the ‘END’ value after every iteration

### Code:

``````for I = eye (3)
disp(‘Value:’)
disp(I)
disp(‘END’)
end``````

This is how our output will look like:

### Output:

If we use it with a break statement, it will break the ‘for loop’ after the first iteration.

### Code:

``````for I = eye (3)
disp(‘Value:’)
disp(I)
break
disp(‘END’)
end``````

### Output:

As we can notice, our loop is ended after the first iteration.

Categories

## for loop in PowerShell

Once you jump into dipper coding you will face various kinds of situation, there may be situations when you required to execute certain expressions or statements repetitive. It may be reading each element of an array or it may be reading each line of a file, in all these cases we need to read again and again. ”for” Loop in PowerShell serve the same purpose, it provides a very powerful mechanism to execute certain code block again and again according to requirements.  For example, an array containing users and we want to check users with the name “Ajay”, so we need to check each element and for that, we need a “for”  loop and once the user “Rajya” found loop will exit. Before going to use ‘for’ loop, always remember loop are very much resource consuming, so we should try to write code in such a way that once we achieved our goal, the loop should stop.

### Syntax:

``````for (<Initial value>; <Condition expression>; <Incremental>)
{
<Statement 1>
<Statement 1>
...
}``````

## 4 Main Sections of for Loop in PowerShell

For loop consists of 4 main sections, explanations are given below:

### 1. Initial value

The initial value is an integer value that starts from 0 to any number, this section executes once for the first time.In this section we initialise variable with initial value,example (\$i = 0),(\$i = 0), (\$j = 0).

### 2. Condition expression

In this part, on each repetition, it checks for condition true or false, so if the condition is true then it will go inside for loop and execute Statement1 and Statement2. Example \$i -lt 10 , here if \$i is less than 10 then Statement1 and Statement2 will execute.

## 3. Incremental

On every iteration value of \$i will get increased, decreased or changed according to operator, examples \$i++ here value will increase by 1 on each iteration,\$i– in this case value will decrease by 1 on each iteration,\$i+2 in this case value of \$i will increase by 2 on every iteration.

### 4. Statement

In this section, one can write a piece of code or some group statement. In this section, we can also write conditions for braking or halting loop according to our requirements.

### Flow diagram

The above diagram clearly shows 3 sections Initialisation, Condition, and Increment. If the value of \$i is less than 10, that means TRUE. So the Statement block will execute which is statement1 and statement2, after that it will go to Increment block and increased the value of \$i by 1. Once the value of \$i will reach to 10 conditions will be FALSE and for loop will stop.

## How for loop works in Powershell?

Once for loop start it first allocate initial value of variable into memory, this happens once when for loop get started. On the each iteration value of \$i will change , along with checking condition(if condition is true or false). An examples below.

for (\$i = 0; \$i -lt 10; \$i++) { Write-Host \$i } .Here it will keep printing 0,1,2,3,4,5…..99 .Here Initial value of \$i was 0 and over each iteration it’s value becomes 1,2,3,4,5,6…100 . Once the value of \$i will reach 100 ,it will stop further execution and it would not print 100 as condition “\$i -lt 100” get failed .

## Examples

Below are the examples mentioned:

### 1. Simple For loop example

`for(\$i=1; \$i -le 10; \$i++){Write-Host \$i}`

## Explanation:

It will iterate for each value of \$i till 10 , since our condition is \$i -le 10 , which is <=(less than equal). So till 10 iterations will continue.Output of Program is 1,2,3,4,5,6,7,8,9,10.

The code execution screen for it is below.

### 2. For loop with a break

In certain situations, we may need to break our loop on specific conditions. In the example below, we are breaking the loop once it reached 12. So the output for code below will be 1,2,3,4,5,6,7,8,9,10,11,12 .

``````for(\$i=1; \$i -le 20; \$i++){
Write-Host \$i
if (\$i -eq 12){
break
}
}``````

The code execution screen for it is below.

### Explanation:

We should always try to find an alternative way instead of nesting for loop, as it’s the time complexity is very high (time complexity is the measure for execution time for any program). For any nested for loop time complexity is O(n^2). A nested loop is a “for loop” within a “for loop” or an inner loop will be the statement for the outer loop. We can put a break in any inner or outer loop to halt the loop.

``````For(\$i=1;\$i -le 5;\$i++){
For(\$j=1;\$j -le \$i; \$j++){
Write-Host "R" -NoNewline
}
Write-Host ""
}``````

The code execution screen for it is below.

### 4. For loop for multiplication table of 25

This is a table of 25, on each iteration, it multiplies 25 with increased number till \$i value reached 10.

``````For (\$i=1; \$i -le 10; \$i++) {
"25 * \$i = \$(25 * \$i)"
}``````

### 5. For loop on the string

In PowerShell length is the keyword to know the length of any string, so here we are checking if the length of a string is less than equals 5 or not(<=5). Once the length of string reached 6, loop exits. So the output id R, RR, RRR, RRRR, RRRRR. Here RRRRRR<=5, which means it reached 6 letters which is larger than 5.

``````For(\$string='' ;\$string.length -le 5;\$string=\$string+'R'){
\$string
}``````

### 6. For loop on the array

``````\$number = “ranjan”,”vijay”,”raj”,”suraj”
for (\$i = 0; \$i -le (\$number.length - 1); \$i += 1) {
\$number[\$i] }``````

Here it is printing all the array memory value from 0-3. So in the first iteration value of \$i was 0 so it prints attribute at 0 location which was “Ranjan”, the same way on the 2nd iteration it prints attribute on the memory location 1 and finally it will print the last attribute on the memory location of 3.

### 7. Infinite loop

Here we are not giving any initial value, we have not given any condition and not even any increment so it will keep printing and will go till infinite.

``````For(  ;  ;  ) {
"Boom Boom Boom"
}``````
Categories

## If Statement

In this article, we will learn about if statement in Matlab. Conditional statements are used to check whether a given condition is true or false and execute the statements accordingly. They are used in many programming languages to execute a line or a code block. If statement is one of the simplest conditional statements. They evaluate an expression or condition and execute the code or statements if the condition is true. If a statement is generally followed by else statement of else if statement in the program.

## Working of if Statement in Matlab with Examples

If statement is a conditional statement that checks if the expression is true or false and accordingly execute the statements. Generally, it is followed by else statement. If the condition is true, then it will execute the code after the if statement but if the condition is false then it will execute the else part. If statements in Matlab are also used in a similar way.

### Syntax:

``````if condition 1
Statement 1
else
Statement 2
end``````

Let us see some examples:

## Example 1:

``````x=5;
If x=5
Y=7;
else
Y=0
end``````

### Output : Y = 7

Here we have assigned x value as 5, so the first statement checks whether x value is 5 or not. In Example 1, the x value is 5 which proves that the condition is true and it will execute the statement after that which is Y= 7 and will display the result of we print it.

## Example 2:

``````x=6;
if x=5
Y = 7
else
Y = 0
end``````

### Output : Y=0

In Example 2, we have assigned the value of x as 6, first statement checks whether the assignment value is correct or not. Since the condition evaluates to false so it will execute the else part in the program and will give the output as Y = 0.

We can also use elseif statement with if statement in the program but the use of elseif is optional and depending on the requirement, we can use it.

### Syntax:

``````if condition
Statement 1
elseif
Statement 2
else
Statement 3
end``````

## Example 3:

``````x = 5;
y = 3;
if (x<y)
z=0;
elseif (x>y)
z=1;
end``````

## Example 4:

``````x=5;
y = 5;
if(x<y)
z=0;
elseif (x>y)
z=1;
else
z=2;
end``````

### Output : z=2

Else if block is used between if statement and else statement. Please find the above two examples describing the working of elseif statement. In Example 3, x and y values are assigned as 5 and 3. First statement checks whether the condition is true or not, here the expression is to check whether x<y which is not true. So, it will skip to the second block and checks the second expression as x>y which is true, so it will execute the subsequent statement and display the output as z =1. This marks the end of the program.

In Example 4, x and y values are assigned as 5. The first expression is x<y which is false, so it will jump to the second block which checks for the second expression x>y which is also false. Since neither of the above two expressions are true it will execute the else block and display the output as 2. This marks the end of the execution.

If statement is for multiple purposes like to compare array or character vectors. Please find the below examples for better understanding:

## Example 5:

### code:

``````limitval = 0.9
x=rand (5,1)
0.921
0.872
0.196
0.223
0.990
If any(x>limit)
Y  = 7;
else
Y = 0;
end``````

### Output : Y = 7

In the above example, the limit is assigned a value as 0.9 and rand function is used to generate random numbers. According to the input arguments in the rand function, it will generate 5 random numbers between 0 and 1. If condition checks whether any value is greater than 0.9 or the value assigned to limit. If there are any values greater, than it will give Y = 7 if we print it. If not then, it will give the statement as given in the else part.

Here the output of the above code is Y= 7 if we print it since 0.921 and 0.990 are greater than 0.9.

## Example 6:

### code:

``````a = 12;
minvalue = 3;
maxvalue = 7;
if (a <= minvalue) &&(a>=maxvalue)
disp (“Hello1”)
elseif (a > maxvalue)
disp(“Hello2”)
else
disp(“Hello3”)
end``````

### Output : “Hello2”

Here if statement is used to check multiple conditions. In the first line of the code, since && operator is used, it checks if both the conditions are met and then only it will execute the consecutive statement. After checking, the result is false so it will check the second condition in elseif line and since it is true, it will display the output as “Hello2” ignoring the else part.

Categories

## If-Else Statement

• If the statement executes code or statement block only when the condition is true. It is a conditional programming keyword used to give conditions to the program on Matlab.
• It has three parts if statement, else statement and else if statement if-else statement in Matlab.
• If the first expression or condition is true then ‘ if ’ statement executes. If the expression is false then else statement executes. And if there are multiple conditions in code then else if the statement is used in Matlab.

### Syntax:

``````If (condition)
Statement
Else
Statement
end``````

## Examples of If-Else Statement in Matlab

Here are some examples of the if-else statement in Matlab which are given below:

### Example 1 – Simple If-Else Statements

let us consider an example to find a large or less than a specific number.

If a = 5 then we will find the number a is less than 10 or not.

### Code:

``````a = 5
if ( a < 10 ) - - - - - condition 1
disp ( ' number is less than 10 ' ) - - - - - condition 1 is true
else
disp ( ' number is large than 10 ' ) - - - - - condition 1 is false
end``````

### Output:

a  =  5

the number is less than 10

Screen 1 shows the Matlab implementation of example 1.

Screen 1: Matlab implementation of example  1

### Example 2 – Comparison of Two Numbers

Consider the second example to find out the maximum of two numbers. Let us take two number  ‘ a ’ and  ‘ b ’.

### Code:

``````a = 10 and b = 15
clc ;
a = 10
b = 15
if ( a > b ) - - - - - condition 1
disp ( ' a is maximum ' ) - - - - - condition 1 is true
else
disp (' b is minimum ' ) - - - - - -condition 1 is false
end``````

### Output:

a =10

b =15

b is maximum

Screen 2 shows the Matlab implementation of example 2.

Screen 2: Matlab implementation of example 2

### Example 3 – Use of Nested if  Statement

In this example, we will see a maximum of three numbers, let us consider three numbers a, b  and c. a = 10 , b = 15 and c = 20.

### Code:

``````clc ;
a = 10
b = 15
c = 20
if ( a > b ) - - - -condition 1
if ( a > c ) - - - nested if condition 2
disp ( ' a is maximum ' ) . . . .if condition 2 is true
else
disp ( ' c is maximum ' ) - - - -if condition 2 is false
end
end
if ( a < b ) - - - - - -condition 3
if ( b > c ) - - - - nested if condition 4
disp ( ' b is max ' ) if condition 4 is true
else
disp('c is max') if condition 4 is false
end
end``````

### Output:

a  =10

b =15

c =20

Ans  =1

c is max

Screen 3 A shows the Matlab code of example 3 and screen 3 B shows the output of example 3.

Screen 3 A: Matlab implementation of 3 A

Screen 3 B: the output of example 3

### Example 4 – Use of Logical Operators

Now let us consider one example to check the given number is within range or not.

In this example, we will see the use of the logical expression in if-else statements.

### Code:

1. If a = 10

``````Clc ;
a = 10
min = 2
max = 20
if ( a > = min ) & & ( a < = max )
disp ( ' a is within range ' )
elseif ( a < = min )
disp ( ' a is less than minimum ' )
else
disp ( ' a is more than maximum value ' )
end``````

### Output:

a =10

min =2

max =20

a is within range

### Code:

``````clc ;
a = 50
min = 2
max = 20
if ( a >= min ) & & ( a < = max )
disp ( ' a is within range ' )
elseif ( a < = min )
disp ( ' a is less than minimum ' )
else
disp ( ' a is more than maximum value ' )
end``````

### Output:

a =50

min =2

max =20

a is more than the maximum value

### Code:

``````clc ;
a = 1
min = 2
max = 20
if ( a > = min ) & & ( a < = max )
disp ( 'a is within range ' )
elseif ( a < = min )
disp ( ' a is less than minimum ' )
else
disp ( ' a is more than maximum value ' )
end``````

### Output:

a =1

min =2

max =20

a is less than a minimum