Call Us On : +91 9873543020    [email protected]

## MATLAB Basics

#### Introduction

In MATLAB basics and implementation, we will cover the basic concepts of the MATLAB programming language and its implementation. This includes installation, paradigm, MATLAB window, variable assignment, arrays in MATLAB and their indexing, etc in great detail. Although this series of the blog is intended to develop a deep understanding of developing MATLAB programs for Image Processing, this section ‘MATLAB Basics’ is equally beneficial for those who want to learn MATLAB programming in other fields.

#### MATLAB Installation

MATLAB is a proprietary programming language, so you have to purchase it. You can follow its official website for installation or you can follow the instructions provided here or here. GNU Octave is one of the major free and open-source alternative software to MATLAB. It resembles almost all of the features and programming structures of MATLAB. You can find the installation guide for Octave here.

#### Programming Paradigm

The paradigm of a programming language is a way of classification on the basis of programming features. There are multiple ways in which one language differs from the other. For example, whether the language is High-level or Low-level? Similarly, whether it is compiled or interpreted? or it supports object-oriented programming or not? etc. The following figure illustrates the position of some of the well-known languages including  MATLAB in the programming paradigm.

The arrow (A –> B) indicates that the compiler/interpreter of language B is written in language A. So the interpreter used in MATLAB (and part of its libraries) are written in C, C++, and Java.

Introduction to MATLAB

MATLAB is a high level, object-oriented and an interpreted language. It is developed by Mathworks primarily for numerical computing. However, it became popular for developing algorithms, creating models and Data Analysis.

MATLAB is the abbreviation for Matrix Laboratory. Therefore, it is preferable to have some basic knowledge of matrices before we discuss the MATLAB basics and implementation. In the previous section of the blog, I’ve discussed the concepts of Matrix and its usage in MATLAB. You can read the blog here.

#### MATLAB Window

Let’s have a look at how a MATLAB  window looks like.

In the figure, you can see four sections or sub-windows in the MATLAB window. There are other sections and windows also that we will discuss later. So let’s discuss these windows briefly.

1. Command Window – This is the main window of MATLAB where you can declare a variable, run a command and get the results. Even for the longer codes written in script files, you’ll get the result in the command window only.
2. Workspace Window – It shows the information about variables currently stored in the MATLAB memory.
3. Editor Window – Here you can write and edit your programs and also save it as a script file. When you write and save a program in the editor, it generates a file with extension .m.
4. Current Folder Window – Here you’ll see the files in the current folder. You can see the path of the current folder in the address bar in Fig. 3.2. When you run a script file and this file is not present in the current folder it will ask for two options- ‘Change Folder’ or ‘Add to Path’. It is preferable to opt for the Change Folder as it will automatically take you to the folder where the file is stored.

There are other windows also, like Figure window for displaying graphical results, Help window for getting help regarding a function or commands, etc. We will discuss them later as we progress.

#### Working on Command Window

Working on the command window is the easiest way of understanding MATLAB syntax and commands. Once you start working in the command window, you’ll realize that you can perform a lot of operations without any prior knowledge of programming. Just to begin with, let’s start with some basic arithmetic operations.

Fig. 3.3 shows a snippet of the MATLAB command window with some of the basic arithmetic operations. Also, there are some variable assignments. For example, a = 5; which means a variable namely a is created and the number 5 is assigned to this variable.

#### Variable Assignment

The following equation shows a general form of variable assignment in MATLAB.

Variable\_name = Numerical\_value  \textbf{or}  Expression

For example,

>> x = 5;
>> y = 2*x + 3;

We use the semicolon to suppress the output. You can observe the missing output display where a semicolon is present at the end in Fig 3.3.
After the assignment of variables a and b (in Fig 3.3), there is an addition operation using these variables. So c = a + b indicates that the variable c stores the summation of values stored in a and b. Similar is the case for the subtraction d = b – a. Since the semicolon is absent in both the operations, you find the display of output values of c and d on the screen.

#### Some Arithmetic operations in MATLAB

The following table shows the list of MATLAB operations with their symbols and examples.

#### Some built-in functions in MATLAB

You can have a look at some of the built-in functions along with their descriptions and examples in the following table.

#### Managing Variables

You can manage the variables that you have created using certain commands. This includes erasing variables, getting information about the variables, etc.

>> clear

This command clears all the variables present in the workspace.

>> clear a b c

The clear command followed by one or more variables deletes only those variables from the workspace. In this example, the command clears the variables a, b and c.

>> who

This command displays the list of variables in the memory.

>> whos

‘whos’ command displays the variables with details including name, size, and a class of the variables. Adding variable name after whos will display information about the specified variables only.

#### Creating Arrays

Arrays are a group of elements associated with a single variable. Like all other programming languages, MATLAB has its own way of creating, addressing and handling arrays. In general, we use the following syntax for creating an array.

Variable\_name = \textbf{[} Array Elements \textbf{]}

For example,

>> A = [3 5 1 4 9 0]
A =                             % output
3  5  1  4  9  0
>> B = [2 5 9 ; 4 1 0 ; 6 2 -1]
B =                             % output
2  5  9
4  1  0
6  2 -1

Here A is a row vector of length 6 and B is a 3×3 matrix. If you wish to create a column vector, you just need to put a semicolon (;) between the elements.

>> a=[1;2;3;4]
a =                 % output
1
2
3
4

Therefore, you should keep the following points in mind while creating arrays.

Row Vector –  First write the name of the vector following an equality sign. And on the right side of it, within the square brackets write the vector elements with spacing. You can insert commas (,) also between the consecutive elements.

Column Vector – Same as row vector except that we insert semicolon (;) between the consecutive elements.

Matrix – Withing the square brackets, elements of a row are written as in the case of a row vector, that is, with spacings. While each of the rows is separated by a semicolon.

Note that if you are not familiar with the terminologies or concept of vector or/and matrix, please refer to the previous section of the blog here before we move on to the MATLAB basics and implementation further. I’ve explained these concepts in detail.

#### Creating special vectors – with constant spacing

You can create a vector with constant spacings between the consecutive elements. There are two ways in which you can do this depending upon the requirements.

1. xi:d:xf – Here xi is the first element, d is the difference between the consecutive elements, and xf is the upper limit of the last element. This syntax is used when you know the first element, the common difference between the consecutive elements, and the upper limit of the last element. So the xf may or may not be the last element of the vector. For example,
>> x = 1:2:9
x =                     % output
1  3  5  7  9
>> x = 2:3:15
x =                     % output
2  5  8  11  14
>> x = 2:0.5:5
x =                     % output
2.0  2.5  3.0  3.5  4.0  4.5  5.0

If you skip the d parameter and use the syntax xi:xf, the default different is taken as 1. For example,

>> x = 1:5
x =                      % output
1  2  3  4  5
>> x = -3:2
x =                      % output
-3  -2  -1  0  1  2

You can use a negative common difference also.

>> x = 10:-2:1
x =                      % output
10  8  6  4  2
>> x = 3:-1:-2
x =                      % output
3  2  1  0  -1  -2
2. linspace(xi,xf,n)– This command is used when you know the first element, the last element and you want to create n number of equally spaced elements in the vector. For example,
>> x = linspace(1,10,5)
x =                                 % output
1.00  3.25  5.50  7.75  10.00
>> x = linspace(-2,6,5)
x =                                 % output
-2  0  2  4  6
>>x = linspace(20,10,6)
x =                                 % output
20  18  16  14  12  10

#### Creating 3D arrays

To create a 3D array, you need to define each plane of the array separately. For example, suppose you want to create an array with dimension (2,3,3). That is, the array has 3 planes and each of them is having 2 rows and 3 columns. Therefore, we need to create three 2D arrays of size (2,3). In MATLAB, addressing the whole elements of a particular plane is done as A(:,:, plane). Here is the name of the array. The first colon (:) indicates all rows, the second colon indicates all columns and the plane indicates the plane number. Array indexing is explained in detail in later sections.

>> A(:,:,1) = [1 2 3 ;4 5 6];
>> A(:,:,2) = [7 8 9 ; 10 11 12];
>> A(:,:,3) = [-1 -2 -3 ;-4 -5 -6];
>> A                         % output
A(:,:,1) =
1     2     3
4     5     6
A(:,:,2) =
7     8     9
10    11    12
A(:,:,3) =
-1    -2    -3
-4    -5    -6

#### Some Built-in Arrays

There are some commonly used built-in arrays in MATLAB.

>> Z = zeros(3,4)
Z =                  % output
0  0  0  0
0  0  0  0
0  0  0  0
>> N = ones(4,4)
N =                  % output
1  1  1  1
1  1  1  1
1  1  1  1
1  1  1  1
>> E = eye(3)
E =                  % output
1  0  0
0  1  0
0  0  1


The command ‘zeros’ produces an array with all elements being zero. The size of the array is specified within the small bracket as – zeros(no_of_rows, no_of_columns).
Similar is the case for ones where all the elements are 1. The ‘eye’ command produces an identity matrix with an equal number of rows and columns specified in the input argument.
Note that within the input arguments of ‘zeros’ and ‘ones’ if you enter only one argument, it will generate a square matrix with an equal number of rows and columns specified in the argument.

#### Array Addressing/Indexing

We have discussed the concept of indexing in the previous section. You can go through it quickly for better understanding.

Indexing is a way of specifying the array elements. For example, consider the following vector V.

>> V = [12 9 0 2 -3 1 8 7];


If we wish to know what the 3rd element of the vector is? so that we can use it in some other array or perform some operation on it, what should we write in the command window? The answer is the following:

>> V(3)
ans =
0


So, the syntax for addressing/indexing an element is

value\_of\_the\_element = variable\_name\textbf{(}element\_position\textbf{)}

>> x = V(5)
x =                  % output
-3
>> y = V(1) + V(5)
y =                  % output
9
>> z = V(2)*V(5)
z =                  % output
-27

Notice the small brackets () used for indexing. Whereas we used square brackets [] for creating arrays.

#### Multiple element indexing

Suppose you need to access the 4th to 7th element from the vector V in the above example. What should be the syntax? Have a look at the following examples.

>> x = V(4:7)
x =                       % output
2  -3  1  8
>> y = V(3:end)
y =                       % output
0  2  -3  1  8  7


#### Matrix Indexing

There are two ways in which elements of a matrix can be addressed – Linear indexing & Subscript indexing. Linear indexing requires only a single parameter for indexing while subscript indexing involves multiple parameters. A (2D) matrix needs two parameters (one for the row and another for column) for indexing.

Linear indexing counts matrix elements column-wise. That is,  you start counting elements of the first column. After the end of the first column, continue the counting from the top of the second column and so on until you reach the last column.

Subscript indexing is relatively simple. You take any of the elements of the array and you find its position in terms of row and column number. The (row, column) pair would be the index of the element. In the case of the 3D array, an additional parameter- ‘plane‘ will be added. So the index of an element of a 3D array would be in the form of (row, column, plane).

The following examples illustrate the indexing methods for matrices.

>> M = [3 4 9 0 ; 14 9 25 1 ; 5 0 8 -3]
M =                                    % output
3   4  9   0
14  9  25  1
5   0  8  -3
>> M(1) % Linear Indexing
ans =
3
>> M(1,1) % Subscipt Indexing
ans =
3
>> M(5) % Linear Indexing
ans =
9
>> M(2,2) % Subscipt Indexing
ans =
9
>> x = M(2,1) - M(1,3)
x =                                    % output
5
>> y = M(1,2) * M(3,4)
y =                                    % output
-12

And the example of a 3D array indexing is as follows.

>> A(:,:,1) = [1 2 3 ; 4 5 6];
>> A(:,:,2) = [7 8 9 ; 10 11 12];
>> A(:,:,3) = [-1 -2 -3 ; -4 -5 -6];
>> A
A(:,:,1) =                        % output
1     2     3
4     5     6
A(:,:,2) =
7     8     9
10    11    12
A(:,:,3) =
-1    -2    -3
-4    -5    -6
% indexing
>> A(4)
ans =
5
>> A(2,2,1)
ans =
5
>> A(8)
ans =
10
>> A(2,1,2)
ans =
10

#### Multiple element Array Indexing

The following examples illustrate the multiple-element array indexing.

>> M = [3 4 9 0 ; 14 9 25 1 ; 5 0 8 -3]
M =                                       % output
3  4  9  0
14  9 25  1
5  0  8 -3
>> M(1,:)  % 1st row, all columns
ans =
3  4  9  0
>> M(3,:)  % 3rd row, all columns
ans =
5  0  8  -3
>> M(:,1)  % All rows, 1st column
ans =
3
14
5
>> M(:,3)  % All rows, 3rd column
ans =
9
25
8
>> M(:,end)  % All rows, last column
ans =
0
1
-3
>> M(2:3,:)  % 2-3 rows, all columns
ans =
14 9 25  1
5 0  8 -3
>> M(2:3,[2 4])  % 2-3 rows, 2 & 4 columns
ans =
9  1
0 -3

You can try multiple array indexing for the 3D array also.

#### Variable Concatenation

Variable concatenation refers to the merger/joining of two or more arrays or merger/joining of one or a few elements to the existing elements of an array. For example,

>> A = [1 2 3 4];
>> A(5:7) = ones(1,3)
A =                                % output
1  2  3  4  1  1  1
>> A = [1 2 3 4];
>> B = ones(1,3);
>> A = [A B] % Horizontal concatenation
A =                                % output
1  2  3  4  1  1  1
% Matrix concatenation
>> A = [1 2 3 4 ; 5 6 7 8]
A =                                % output
1  2  3  4
5  6  7  8
>> A(3,:) = 2:3:11
A =                                % output
1  2  3  4
5  6  7  8
2  5  8  11
>> B = eye(3)
B =                                % output
1  0  0
0  1  0
0  0  1
>> A = [A B]
A =                                % output
1  2  3  4  1  0  0
5  6  7  8  0  1  0
2  5  8  11 0  0  1


#### Transpose of an array

MATLAB uses an apostrophe ( ‘ ) following the variable name for transposing an array. For example,

>> A = [1 2 3 4]
A =                           % output
1  2  3  4
>> B = A’
B =
1
2
3
4
>> A = [1 2 3 ; 4 5 6 ; 7 8 9 ];
A =                           % output
1  2  3
4  5  6
7  8  9
>> B = A’
B =                           % output
1  4  7
2  5  8
3  6  9


#### Deleting Elements

You can delete one or more elements from an array. All you need to do is, mention the indices of the array you wish to delete and use [] after the equality sign. For example,

>> A = [4 9 2 -1 0 3 7 1]
A =                                   % output
4  9  2  -1  0  3  7  1
>> A(3) = [] % [] used for deleting array elements
A =                                   % output
4  9  -1  0  3  7
>> A(4:6) = []
A =                                   % output
4  9  -1
>> A = [4 9 2 -1 0 ; 3 7 1 -5 4 ; 0 8 9 5 1]
A =                                   % output
4  9  2 -1  0
3  7  1 -5  4
0  8  9  5  1
>> A(:,2:4) = []
A =                                   % output
4  0
3  4
0  1


#### Handling arrays using built-in functions

Once you have created the arrays, you can handle these using some built-in functions. This includes obtaining the size and shape of the arrays, reshaping arrays finding diagonal of a 2D array, etc.

#### Length of an array

Function – length(A)
Description – Finds the total number of elements in a vector. If the input is a matrix, it returns the largest dimension of the matrix.

>> A = [2 4 9 0 3];
>> length(A)
ans =
5
>> B = [1 2 ; 3 4 ; 5 6]
B =                      % output
1 2
3 4
5 6
>> length(B)
ans =
3


#### Size of an array

Function – size(A)
Description – Returns dimension of an array. If the array is a vector or a 2D matrix, the output will be a vector of length 2 containing the number of rows and columns. If the input is a 3D array, it returns a vector of length 3 containing the rows, the columns, and the planes.

>> A = [2 4 9 0 3 ; 3 1 2 -5 0]
A =                % output
2 4 9  0 3
3 1 2 -5 0
>> size(A)
ans =
2 5


#### Reshaping and array

Function – reshape(A,m,n)
Description – Reshaping of array A to the dimension mxn. The process of reshaping is also carried out column-wise. That is, MATLAB takes the first column from the existing array and places it into the first column of the output array. If some of the elements are remaining from the source or the output array, it gets adjusted in the next column and so on. For example,

>> A = [2 3 4 ; 5 6 7]
A =                       % output
2  3  4
5  6  7
>> B =reshape(A,3,2)
B =                       % output
2  6
5  4
3  7


#### Diagonal of an array

Function – diag(A)
Description – If A is a vector, the output will be a diagonal matrix with diagonal elements formed using vector A and the rest of the elements of the matrix being 0. On the other hand, if A is a square matrix it returns the diagonal elements of the matrix.

>> A = [1 5 9];
>> diag(A)
ans = 1 0 0
0 5 0
0 0 9
>> B = [1 2 3 ; 4 5 6 ; 7 8 9];
B =                         % output
1  2  3
4  5  6
7  8  9
>> diag(B)
ans =
1  5  9



#### The inverse of an array

Function – inv(A)
Description – Evaluates inverse of a square matrix. The inverse is a very important operation used in solving mathematical problems. For example, solving linear equations. Suppose, we need to solve the following equation. We can write this equation in matrix form in two ways:

These equations can be solved as follows:

Let’s solve this using MATLAB

>> 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]
B =                              % output
16
-5
-3
>> A_inv = inv(A)
A_inv =                          % output
3.5  8.0  5.0
-2.0 -5.0 -3.0
1.0  2.0  1.0
>> X = A_inv*B
X =                           % output
1
2
3

Similarly, you can verify the other form of the solution as well.

#### Strings

Strings are the array of characters. We write strings within single quotes. For example, ‘john’, ‘abc_07’, ‘my name is Adam’, etc. Every single character is regarded as an element of the string. Therefore, all the operations and rules apply to the strings similar to a normal array.

>> a = ‘my_name’
a =                      % output
‘my_name’
>> a(2)
ans =
‘y’
>> a(4:end)
ans =
‘name’
>> length(a)
ans =
7
>> a(8:10) = ‘_is’
a =
‘my_name_is’
>> b = ‘_john’;
>> a = [a b]
a =                      % output
‘my_name_is_john’


Ok, so now we have developed a sufficient background of the MATLAB basics and implementation. In the next section, we will discuss the mathematical operations on the arrays.

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.