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

## MATLAB Basics: Mathematical Operations

##### Welcome to the series of blogs on Digital Image Processing using MATLAB. If you are looking for complete guidance in understanding the concepts of the digital images and image processing using MATLAB, you’re at the right place! In this series, we will discuss the concepts of Image Processing along with the implementation from scratch to the advanced level.  In this blog- MATLAB basics: Mathematical operations- we will discuss the mathematical operations on arrays.

Before we discuss the current topic- MATLAB basics: Mathematical operations, I would recommend you to go through the previous sections of the series for better understanding. The concepts of matrices and arrays are discussed here. Then we have introduced the basics of MATLAB including installation, MATLAB windows, basic syntax, concepts of arrays, array indexing, etc., here. In this section, we will discuss various mathematical operations on arrays. We’ll also discuss the generation of random numbers in MATLAB. So let’s start the MATLAB basics: Mathematical operations.

#### Mathematical operations on Arrays

We can perform various mathematical operations on arrays in MATLAB. For example, addition/subtraction of two arrays, scalar/matrix multiplication on arrays, etc. However, there are some conditionalities and rules for the array operations. Let’s discuss them one by one.

The condition for the addition and subtraction of two arrays is that the dimensions of both the arrays should be the same.  The syntax is the same as normal addition and subtraction, i.e, +/-. For example,

```>> A = [9 1 0 2 3];
>> B = [3 4 -1 5 4];

>> C = A + B
C =                    % output
12  5  -1  7  7

>> D = A - B
D =                    % output
6 -3 1 -3 -1
>> E = [1 2 3; 4 5 6; 7 8 9]
E =                    % output
1  2  3
4  5  6
7  8  9
>> F = [1 4 7; 2 5 8; 3 6 9]
F =                    % output
1  4  7
2  5  8
3  6  9
>> G = E + F
G =                    % output
2  6  10
6  10 14
10 14 18
>> H = F - E
H =                    % output
0  2  4
-2  0  2
-4 -2  0
```

Above examples illustrate addition/subtraction of one array to the other. What if an array is added/subtracted with a scaler (a single number)? The answer is – the scaler gets added/subtracted by all the elements of the array. For example,

```>> A = [9 1 0 2 3];
>> B = A + 4
B =                       % output
13  5  4  6  7
>> C = B – 6
C =                       % output
7  -1  -2  0  1
>> A = [1 2 3; 4 5 6; 7 8 9]
A =                       % output
1  2  3
4  5  6
7  8  9
>> B = A + 5
B =                       % output
6   7   8
9  10  11
12  13  14
>> C = B - 10
C =                       % output
-4   -3   -2
-1    0    1
2    3    4
```
2. #### Multiplication

There are two types of array multiplication- Scaler and matrix multiplication. Let’s explore both of them.

• Scaler multiplication – In scalar multiplication, the scaler gets multiplied by each of the array elements. For example,
```>> A = [1 2 3;4 5 6;7 8 9]
A =	                    % output
1  2  3
4  5  6
7  8  9
>> B = 5 * A
B =	                    % output
5  10  15
20  25  30
35  40  45```
• Matrix multiplication – The condition for matrix multiplication of two arrays/matrices is- “the number of columns in the first matrix should be equal to the number of rows in the second matrix”. Also, the dimension of the resultant array would be r1xc2. Where r1 is the number of rows in the first matrix and c2 is the number of columns in the second matrix. MATLAB uses * sign for multiplication of arrays. For example,
```>> A = [1 2 3;4 5 6;7 8 9]  % dimension- 4x3
A =		            % output
1  2  3
4  5  6
7  8  9
0 -1 -2
>> B = [4 3;3 2; 2 1]  % dimension- 3x2
B =                         % output
4  3
3  2
2  1
>> C = A * B   % dimension- 4x2
C =                         % output
16  10
43  28
70  46
-7  -4```

You can go through the matrix multiplication procedure in the previous section of matrix basics here.

3. #### Division

Matrix division is in fact, the multiplication of one matrix with the inverse of the other. Therefore, the division of two matrices A and B is equivalent to A.(B-1). In this context, matrix division is classified into two types based on the order of multiplication.

• Left Division – when we multiply the inverse of a matrix by another matrix. For example, X = A-1B. Refer to the first example of Fig. 4.1 for understanding the left division. The operator for the left division is \. Therefore, instead of inv(A)*B, we can use A\B to get the same results.
```>> A = [2 4 2;-2 -3 1; 2 2 -3]
A =                       % output
2  4  2
-2 -3  1
2  2 -3
>> B = [16; -5; -3];
>> X = A\B
X =                    % output
1
2
3```
• Right Division – when we multiply a matrix by the inverse of another matrix. For example, X = BA-1, the second form of multiplication in the example of Fig 3.4. In that case, the solutions of the 0linear equation would be,
```>> A = [2 -2  1;4 -3  2; 2 1 -3]
A =                            % output
2 -2  2
4 -3  2
2  1 -3
>> B = [16 -5 -3]
B =                            % output
16 -5 -3
>> A_inv = inv(A)
A_inv =                        % output
3.5  -2.0   1.0
8.0  -5.0   2.0
5.0  -3.0   1.0
>> X = B*A_inv
X =                            % output
1  2  3

>> X1 = B/A
X1 =                           % output
1  2  3```
4. #### Element-wise operations

It involves the element to element operation between arrays. The condition for the element-wise operation is that the dimensions of the arrays involved should be the same. The syntax for the element-wise operations would be the same as normal operations except that a dot (.) is placed before the operator. For example, A.*B implies element-wise multiplication of the arrays A and B. The following figure shows the list of element-wise operations with examples.

#### Built-in Functions for analyzing Arrays

There are some useful functions in MATLAB for analyzing the properties of arrays. This includes finding the minimum and maximum values in the arrays, obtaining statistical parameters like mean, median, etc. Let’s discuss some of them.

#### max() and min()

These functions return elements with maximum/minimum values in the array. If the input is a vector the output will be a single number. However, in the case of a matrix, it returns a vector containing the maximum/minimum elements of each of the columns of the matrix. For example,

```>> x = [8 0 1 9 3 -2];
>> y = max(x)
y =                           % output
9
>> z = min(x)
z =                           % output
-2
>> x = [4 4 7;3 8 0;-1 0 8]
x =                           % output
4  4  7
3  8  0
-1  0  8
>> y = max(x)
y =                           % output
4  8  8
>> z = min(x)
z =                           % output
-1  0  0
```

Sometimes we need to know the index of the maximum/minimum element(s) also. For that, you need to take two output arguments. For example,

```>> x = [8 0 1 9 3 -2];
>> [y,id] = max(x)
y =                     % output
9
id =
4
>> [z,id1] = min(x)
z =                     % output
-2
id1 =
6
```

You can check this for the matrices also.

#### mean() and median()

These functions return the statistical values of the array elements. The output for a vector and a matrix differ the same as the explained for the min/max operations.

```>> x = [2 3 9 1 4 0];
>> y = mean(x)
y =                           % output
3.1667
>> z = median(x)
z =                           % output
2.5
>> x = [4 4 7;3 8 0;-1 0 8]
x =                           % output
4  4  7
3  8  0
-1  0  8
>> y = mean(x)
y =                           % output
2  4  5
>> z = median(x)
z =                           % output
3  4  7
```

#### sum()

sum(X) returns the sum of the elements of array X if it is a vector. On the other hand, if X is a 2D matrix, it returns a vector containing the sum of each of the columns of the matrix. For example,

```>> x = [8 0 1 9 3 -2];
>> y = sum(x)
y =                          % output
19
>> x = [4 4 7;3 8 0;-1 0 8]
x =                          % output
4  4  7
3  8  0
-1  0  8
>> y = sum(x)
y =                          % output
6  12  15
```

#### sort()

sort(X) returns the sorted elements of the array X. If X is a vector, the output will be a sorted vector. However, if X is a matrix, sort() will return the matrix of the same size with sorted columns. For example,

```>> x = [8 0 1 9 3 -2];
>> y = sort(x)
y =                            % output
-2  0  1  3  8  9
>> x = [4 4 7;3 8 0;-1 0 8]
x =                            % output
4  4  7
3  8  0
-1  0  8
>> y = sort(x)
y =                            % output
-1  0  0
3  4  7
4  8  8
```

Just like min() and max() functions, sort() has also the feature of getting indices of the sorted elements. You just need to add extra output arguments. For example,

```>> x = [8 0 1 9 3 -2];
>> [y,idx] = sort(x)
y =                              % output
-2  0  1  3  8  9
idx =
6  2  3  5  1  4```

You can try this for matrices also. Note that the function sorts the array elements in ‘ascending’ order. If you wish to sort the elements in descending order, you just need to add one input argument ‘descend’. For example,

```>> x = [8 0 1 9 3 -2];
>> [y,idx] = sort(x,'descend')
y =                              % output
9  8  3  1  0  -2
idx =
4  1  5  3  2  6
```

#### Some more built-in functions

The figure below lists a few more built-in functions.

#### Random number generation

The generation of random numbers is one of the key tasks in programming. Random numbers are used in optimization problems, encryption algorithms, node deployment in wireless sensor networks and many key areas. The algorithm that generates the sequence of random numbers is known as the Pseudo-Random Number Generator (PRNG). You can generate random sequences in MATLAB using the following functions.

1. #### rand()

Generates uniformly distributed random numbers between 0 and 1.

```>> rand
ans =
0.8550
>> rand(1,5)
ans =
0.4654  0.2648  0.6295  0.5627  0.5412
>> rand(3)
ans =
0.6093  0.4002  0.5063
0.8918  0.5539  0.5872
0.4208  0.5963  0.1328
```

By uniformly distributed we mean that if you generate a large sequence of random numbers using rand() and plot the frequency versus values of these numbers, you’ll get a uniform curve. For example, consider the following graph.

Here we have split the values (between 0-1) into small bins in the x-axis. Then we have counted how many numbers (generated using rand) lie in each of the bins. You can observe that the random numbers in each bin are almost uniform.

2. #### randn()

Generates normally distributed random number with μ = 0, σ = 1

```>> randn
ans =
0.0861

>> randn(1,5)
ans =
-0.3837  -1.2248  1.7484  0.2119  0.7812

>> randn(3,4)
ans =
1.6713   -0.0762    0.1543    0.7713
-0.1636   -1.6701   -0.1792    0.1673
-0.8184   -0.9727    1.6964    0.4363
```

You can go through the concept of normal distribution here. So when you plot frequency versus values graph for random numbers generated using randn(), you’ll get the following distribution.

3. #### randi(imax)

Generates random intergers between 1 and imax.

```>> randi(10)
ans =
6
```

randi(imax,m,n) – generates random integers between 1 and imax. of size mxn.

```>> randi(20,1,5)
ans =
12  10  7  17  16
>> randi(10,3,4)
ans =
5     3     7     8
10     3     3     6
9    10     2     2
```

randi([imin imax],m,n)- generates random integers between imin and imax.

```>> randi([10 20])
ans =
17
>> randi([5 15],1,5)
ans =
5  7  15  5  13

>> randi([0 1],4)
ans =
1     0     1     1
0     1     1     0
1     1     1     1
0     1     0     1```

This concludes the section of mathematical operations on arrays. In the next sections, we will discuss how to make a script file in MATLAB. Afterward, we will learn the interesting feature of MATLAB, that is, plotting. MATLAB provides a very interesting and interactive platform for plotting the data and images. We will also learn to create user-defined functions in MATLAB.

Thank you.

Contact us!

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