Call Us On : +91 7042 195 641  [email protected]

## Introduction

A program is a collection of commands. These commands are written serially according to the simulation requirements. Sometimes, we need to perform repetitive tasks on multiple elements of a variable. For example, replacement of the image pixels with the average of neighbor pixels (image smoothing), repeating the calculation until the error is less than a threshold (numerical computing), etc. We use loops to perform these operations in the program. There are two kinds of loops in MATLAB: for loop and while loop.

Sometimes we need to check for the conditions before executing a command. For example, to check whether a number is prime or not before proceeding to the next operation, to check whether a node is within the transmission range R of the antenna or not (in WSN), etc. These conditions are applied using conditional statements. if-else, if-elseif, and switch-case are the conditional statements in MATLAB.
To apply the conditional statements, we need some relational and logical operators. For example, less than (<), greater than (>), AND operator, OR operator, etc.

Therefore, the flow of commands works in the following order: 1) Relational and Logical operators are used within the Conditional statements, 2) these conditional statements can be used anywhere in the program within the loops. However, relational and logical operators can be used without conditional statements also. Let’s discuss these in detail.

## Relational and Logical operators

A relational operator compares the values within the statement and returns the output as 1 (True) or 0(False). For example, 6>2 returns 1 and 3==4 returns 0. Before moving on to the examples, let’s explore the list of the MATLAB relational operator syntax.

We can use the relational operators on variables also. For example,

```>> a = 3;
>> b = 4;
>> c = a < b
c =
0
>> a = [10 7 0 5 14 6 10];
>> b = [9 18 8 4 17 5 13];
>> d = a>=b
d =
1  0  0  1  0  1  0
>> A = [3  7  5
-2  6  3
5  6 -3];
>> B = A < 4
B =
1  0  0
1  0  1
0  0  1```

Apart from the relational operators, there are three logical operators- AND, OR & NOT.

You can also use and(A, B), or(A, B), and not(A) for the respective operations. Consider the following examples.

```>> 1 & 3
ans =
1
>> 2 & 0
ans =
0
>> 0 | 5
ans =
1
>> ~1
ans =
0
>> a = [1 0 1 3 0];
>> b = [0 2 1 0 0];
>> c = a & b
c =
0  0  1  0  0
>> d = a | b
d =
1  1  1  1  0
>> e = ~a
e =
0  1  0  0  1
>> and(0,1)
ans =
0
>> or(1,0)
ans =
1
>> not(3)
ans =
0```

## Conditional Statements

A conditional statement is a command that decides whether to perform a task (or a group of tasks) or not. MATLAB uses the ‘if’ statement to check the conditionality.  There are four types of if statements depending on the conditions.

1. if-end
2. if-else-end
3. if-elseif-end
4. if-elseif-else-end

The following examples illustrate the usage of if statements.

```% To check if a number is even
num = 6;
if rem(num,2) == 0
fprintf('number is even \n')    % \n is used for new line
end
% here rem(a,b) is a function that returns the remainder of a/b

% To check if a number is even or odd
num = 5;
if rem(num,2) == 0
fprintf('number is even \n')
else
fprintf('number is odd \n')
end

% To check if a number is less than, or equal to, or greater than 10
num = 9;
if num < 10
fprintf('number is less than 10 \n')
elseif num == 10
fprintf('number is equal to 10 \n')
else
fprintf('number is greater than 10 \n')
end```

## The switch-case statement

The switch-case statement is another way of directing the flow of the program. In the previous section, we saw how the program selects one condition out of several using the if-else operations. But when the number of options is plenty, using if-else is not suitable. The switch-case statement has relatively compact syntax where mentioning multiple conditions is easier.

Suppose var is the variable whose different values correspond to the different conditions and its values are val1, val2, and val3. The syntax of the switch-case statement would be as follows.

The following example illustrates the usage of switch-case. The task is to print the type of geometrical objects based on the number of sides. For example, print triangle for side=3, rectangle for side=4, and so on and for more than 5 sides, print circle.

```sides = input('Enter the number of sides');

switch sides
case 3
print('triangle')
case 4
print('rectangle')
case 5
print('pentagon')
otherwise
print('circle')
end```

## Loops

Loops are used to perform repetitive tasks. The program updates the values of the variables in each loop until the end of the loop. Let’s discuss the most commonly used loop, the for-end loop.

### for-end Loop

This loop is used when the number of loops is predefined. The most general syntax of the for-end loop is as follows.

Here f is the first value to be used within the loop and l is the last one. s is the increment/decrement by which the next value is increased/decreased and i is the variable where these values are stored in each loop. You can skip if the value of the increment is 1. Let’s take an example of the for-end loop for better understanding. The task is to find the square of every second element of the given vector and display it.

```vec = [2 1 3 4 7 5];

for i = 1:2:length(vec)
sqr = vec(i)^2
end

% output

4
1
9
16
49
25```

Here the values stored in the variable i are used as the indices of the vector elements.

### while-end Loop

while loop is used when the number of loops is not known in advance. The number of loops is decided by the conditional used with the while statement. The general syntax of the while-end loop is as follows.

The conditionals comprise of the statements for which the loop is to be continued. For example, finding the largest integer whose square is less than 100. The following snippet illustrates the example.

```num = 1;
sqr = num^2;

while sqr<100
num = num + 1;
sqr = num^2;
end

largest_num = num-1

% output
largest_num =
9
```

Here we start from num=1 and find its square. The loop will continue till the conditional (sqr<100) is true and when it becomes false, the program comes out of the loop.

### Nested Loop

Nested loop refers to the loop within a loop. So within every (outer) loop, another (inner) loop is executed. The general syntax of the nested-loop is as follows.

Nested loop has many applications but the most commonly used is the handling of the two-dimensional array. For example, squaring each element of a 2D matrix requires the nested loop (Although other methods are also available for this task in MATLAB without using a loop). The outer loop handles the rows of the matrix while the inner loop handles each column within a row.

```M = [1  2  3;
4  5  6;
7  8  9];

[r,c] = size(M); % finding rows and columns of the matrix
Output = zeros(r,c); % Initializing the output matrix of size of the input

for i = 1:r
for j = 1:c
Output(i,j) = M(i,j)^2;
end
end

disp(Output) % display the output

% output
M =
1   4   9
16  25  36
49  64  81```

### The break and continue commands

These commands are used to control the loop operations under certain circumstances. You can use the break command to exit the loop beforehand after fulfilling certain criteria. For example, adding the elements of a vector until you get a negative number. To do this, add the elements using the for loop but also check for the negative element in every loop. If so, use the break command to exit the loop.

```vec = [4 3 7 0 8 9 -1 2 1 7];

sum = 0;
for i = 1:length(vec)
if vec(i) < 0
break
end
sum = sum + vec(i);
end
sum```

On the other hand, continue is used to skip a loop after a certain condition is met. For example, add the elements of a vector except for the negative ones. In this case, you need to use the continue command every time you find a negative element to skip that loop.

```vec = [3 6 -2 0 4 8 7 -5 2 6 -1];

sum = 0;
for i = 1:length(vec)
if vec(i) < 0
continue
end
sum = sum + vec(i);
end
sum```

This completes the discussion on MATLAB loops. We’ll now move on to the application-based programming in MATLAB from the next tutorial.

Thank you.

Contact us!

For training, Research Assistance, and Consultancy Services on Computer Vision, Machine Learning, Deep Learning, Signal Processing, Image Processing, and Medical Signal/Image Processing.