2. WHAT IS MATLAB
A product of MathWorks Incorporation, USA
MathWorks is the leading developer of
mathematical computing software for engineers
and scientists.
MATLAB is a platform, comprising of
A programming Language
An integrated development environment
An interpreter based efficient execution engine
3. Brief History
Cleve Moler, the chairman of the computer science department at the
University of New Mexico, started developing MATLAB in the late 1970s
Recognizing its commercial potential, their team of trio (Cleve Moler, Jack
Little and Steve Bangert) rewrote MATLAB in C and founded MathWorks in
1984 to continue its development
In 2000, MATLAB was rewritten to use a newer set of libraries for matrix
manipulation
MATLAB was first adopted by researchers and practitioners in Control
Engineering, but later it quickly spread to many other domains
It is now also used in education, in particular the teaching of linear algebra
and numerical analysis and very popular amongst scientists involved in the
field of Image Processing, Computer Vision, Artificial Intelligence, Robotics,
Mechatronics, Digital Signal processing, Parallel Computing and almost all
other domains of scientific computing
4. Why MATLAB
It is a high level language cum platform
Syntax is very simple
It has a rich set of libraries and development
tools in the form of toolboxes and toolsets
It is very easy to learn
5. MATRIX Laboratory
All the variables/data objects declared in it are
in the form of MATRIX
Even if the variable is single element, it will be
of type MATRIX i.e. of size 1 by 1 i.e. 1 row
and 1 column
Case sensitive, i.e. a data object “a” will not be
same as “A”
Rich set of statements for handling and
performing different operations on the data
6. Different sections of IDE
Directory window: Shows the contents of existing
directory/folder
Editor window: To display the editor
Command window: Where commands can be
written and directly executed on MATLAB engine
Workspace: Shows all the existing variables/data
objects
History window: History of the commands
executed so far
Current folder: To show/edit current working folder
also called as PWD i.e. Present Working Directory
7. Basic Commands to work in
command window
clc
Clear the screen
close all
To close all existing open windows
clear all
To clear all or particular existing variables/data objects i.e.
Its associated memory is freed
PWD
Present working directory
dir
To show the contents (files/folders) of the present working
directory in command window
8. Writing the program
In the command window, type edit
Editor will open
Write your program and save in the current
folder with the desired name
The extension of the MATLAB program file i.e.
Source code is .m
9. Compilation
Unlike other high level languages e.g.
C++/Java, in MATLAB there is no need of
explicit compilation of your program
MATLAB is an interpreter based platform, i.e.
Execution is done line by line in the MATLAB
engine
So execution will be stopped at the point,
where ever it encounters error or until it has
finished executing the whole program
We can demonstrate it with the help of an
example in MATLAB
10. Executing the Program
Open the command window
The name of the file to be executed should be
visible in the “current folder” section of
MATLAB IDE
Type the name of the file without extension in
the command window
File will be executed, and output displayed if
any
Program can also be executed by “run” button
in the editor
However to view if there is any output, you will
have to switch to command window
11. Using Variables
Simple commands
a=10
b=‘Hello’;
No need to explicitly declare the variables data
type
It is by default considered by the compiler
based on the value assigned
E.g. In above a will be considered as double
and b as character
Double is the default numeric data type
12. Use of Semicolon
What is use of semicolon at the end of the
statements in MATLAB? Is it part of syntax?
Is it mandatory
Answer: No
It is used just to suppress displaying the output
of the statement
i.e. If semicolon put then output is not
displayed, otherwise output (if any) will be
displayed
13. How to check all the existing data
objects along with their “class”
By using the command “whos”
In MATLAB, class means “data type”
Sample output
Name Size Bytes Class Attributes
a 1x5 10 char
b 1x1 8 double
d 1x1 8 double
14. Printing the message or
variable
Using the command “disp”
disp(‘Hello MATLAB’)
disp(a)
Just by writing the name of the variable
(without semicolon) in command window
Using the command “fprintf” (Equivalent of
printf statement of C Language)
fprintf('The value of a = %dn',a);
%d: class specifier, to display the double value
n: Escape sequence for the new line
15. Taking input from user (Text
mode)
Function to be used
input
Syntax
Variable_name=input(‘Message String’,[‘s’]);
Example (For numeric input)
a=input(‘Enter the value of a’);
Example (For character/string input)
a=input(‘Enter the value of a’, ’s’);
16. Writing Loops
For loop
Syntax
for variable_name=index_start:[interval]:index_end
loop body..
.....
end
Example
for i=1:2:30
disp(i)
end
Default value of interval is taken as unity
17. Writing Loops
While loop
Syntax
while(logical expression)
loop body..
.....
end
Example
i=10;
while(i<30)
disp(i);
i=i+1;
end
18. Conditional Branching
if instruction
Syntax
If (logical expression)
....
end
Example
a=input(‘Enter the value of a’);
If (a<10)
disp(‘value of a is less than 10’);
end
19. Conditional Branching (contd.)
if-else instruction
Syntax
If (logical expression)
....
else
....
end
Example
a=input(‘Enter the value of a’);
If (a<10)
disp(‘value of a is less than 10’);
else
disp(‘value of a is greater than or equal to 10’);
end
20. Conditional Branching (contd.)
if-elseif instruction (Multiple conditions to be checked)
Syntax
If (expression1)
.......
elseif (expression2)
.......
elseif (expression3)
.......
.
.
else
........
end
Example
a=input(‘Enter the value of a’);
If (a<10)
disp(‘value of a is less than 10’);
elseif(a==10)
disp(‘value of a is equal to 10’);
else
disp(‘value of a is greater than 0’);
end
21. Matrices and Arrays
MATLAB is an abbreviation for "matrix
laboratory."
While other programming languages mostly
work with numbers one at a time, MATLAB is
designed to operate primarily on whole
matrices and arrays
"matrix" typically refers to a 2
dimensional array
Whereas an "array" can be n-dimensional
Any variable declared in MATLAB is by default
in the form of matrix only.
22. Array Creation
a = [1 2 3 4]
This type of array is a row vector of size 1 by 4
a = [1 2 3; 4 5 6; 7 8 10]
a = 3×3 Matrix
1 2 3
4 5 6
7 8 10
Note that semicolon has been used to initiate new
row
23. Array Creation (contd.)
Another way to create a matrix is to use a function,
such as ones, zeros, or rand.
For example, create a 5-by-1 column vector of zeros.
z = zeros(5,1)
Output
z = 5×1
0
0
0
0
0
24. Array Creation (contd.)
To create a matrix of random numbers
Function used: magic
Example
A = magic(4)
A = 4×4
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
colon operator is used to create an equally spaced vector of values
using general form start:step:end
Example
B = 0:10:100
B = 1×11
0 10 20 30 40 50 60 70 80 90 100
25. Matrix and Array Operations
MATLAB allows you to process all of the values in a matrix
using a single arithmetic operator or function.
a + 10
ans =
11 12 13
14 15 16
17 18 20
sin(a)
ans =
0.8415 0.9093 0.1411
-0.7568 -0.9589 -0.2794
0.6570 0.9894 -0.5440
26. Matrix and Array
Operations(Contd.)
a = [1 2 3; 4 5 6; 7 8 10]
a =
1 2 3
4 5 6
7 8 10
To transpose a matrix, use a single quote (‘
a’
ans =
1 4 7
2 5 8
3 6 10
27. Matrix and Array
Operations(Contd.)
Multiplication
Multiplication is of two types
Matrix multiplication
Operator used is *
E.g. A*B will multiply matrix A and B
Element by element multiplication
Operator used is .*
E.g. A.*B will multiply matrix A and B, elementwise
28. Ways to Access Array
Elements
Unlike other languages like C/C++ and JAVA in
which array indexing begins with 0, in MATLAB
it begins with 1
Description Example Description
Using specific row and
column
A(4,2) To access 2nd
element of 4th row
To use a single subscript
that traverses down each
column in order
A(8) Index converted to
linear value
columnwise
Accessing a range of rows
and columns
A(1:3,2) Elements of rows 1
to 3 and column 2
Accessing all the values in
particular dimension
A(3,:) Accessing all the
elements of row 3
29. Workspace Variables
The workspace contains variables that you create within or
import into MATLAB from data files or other programs. For
example, these statements create variables A and B in the
workspace.
A = magic(4); B = rand(3,5,2);
You can view the contents of the workspace using command
whos
Name Size Bytes Class Attributes
A 4x4 128 double
B 3x5x2 240 double
The variables also appear in the Workspace pane on the
desktop
30. Saving Variables of
Workspace
Workspace variables do not persist after you exit
MATLAB. Save your data for later use with
the save command as below
save myfile.mat
Note that extension of file has to “.mat”
Restore data from a MAT-file into the workspace using load
load myfile.mat
Save command can be used to store particular variables too
as below:
save(filename, variables)
Example
save test.mat X
Above command will save only the variable X to file test.mat
31. Loading data from Excel File
Function to be used: xlsread
Syntax
Variable_name=xlsread(Name of excel file in single
quotes)
Example
num=xlsread(‘test1.xls’)
Output (the contents of excel file loaded in workpace
variable “num”)
num =
10 11 12
11 12 14
12 13 16
13 14 18
32. Loading data from Excel File
Another variant of xlsread
Syntax
Variable_name=xlsread(Name of excel file in single
quotes, sheet)
Example
num=xlsread(‘test1.xls’,’sheet2’)
Output (the contents of sheet2 of excel file loaded in
workpace variable “num”)
num =
10 11 12
24 12 11
38 13 10
52 14 9
33. Loading data from Excel File
Another variant of xlsread
Syntax
Variable_name=xlsread(Name of excel file in single
quotes, sheet,range of cells in single quotes)
Example
num=xlsread(‘test1.xls’,’sheet2’,’B2:C4’)
Output (the contents of cells in the range of B2 to B4 to
and C2 C4 of sheet2 of excel file loaded in workpace
variable “num”)
num =
12 11
13 10
14 9
34. Storing data to Excel File
Function to be used: xlswrite
Different variants of xlswrite
xlswrite(filename,A)
Writes the variable A to excel file, in first sheet (default)
xlswrite(filename,A,sheet)
Writes the variable A to excel file, in specified sheet
xlswrite(filename,A,xlRange)
Writes the variable A to excel file, in default sheet in given range of cells
xlswrite(filename,A,sheet,xlRange)
Writes the variable A to excel file, in specified sheet in given range of cells
status = xlswrite(___)
Returns the status=1 in case write is successful, and 0 in case of failure
[status,message] = xlswrite(___)
Additionally displays the message if generated by the write operation, which is loaded in
variable message
Further advanced versions of xlsread and xlswrite are functions readtable
and writetable respectively.
35. Storing data to Excel File
Another variant of xlsread
Syntax
Variable_name=xlsread(Name of excel file in single
quotes, sheet,range of cells in single quotes)
Example
num=xlsread(‘test1.xls’,’sheet2’,’B2:C4’)
Output (the contents of cells in the range of B2 to B4 to
and C2 C4 of sheet2 of excel file loaded in workpace
variable “num”)
num =
12 11
13 10
14 9
36. Plotting
Function to be used: plot
Syntax
Plot(X,Y): It will plot row vector Y versus row
vector X
The length i.e. Number of elements of both vector
should be same
Example
X=[1 2 3 4 5 6] % Created a vector X
Y=[2 2 3 4 7 9] % Created a vector Y
plot(X,Y)
38. Plotting (Contd.)
xlabel: to add the label to x-axis
xlabel(‘label of the x axis’);
ylabel: to add the label to y-axis
ylabel(‘label of the y axis’);
Title: to give title to the plot
title(‘title of the plot’);
Example
xlabel(‘X axis’);
ylabel(‘Y axis’);
Title(‘A demo Plot’);
40. Plotting (contd.)
Combining multiple line plots into single plot,
single figure
plot(X1,Y1,...,Xn,Yn)
Example code
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
figure
plot(x,y1,x,y2)
42. Plotting (contd.)
Create Line Plot From Matrix
Example code
%Creating a 4 by 4 matrix of random numbers
Y = magic(4)
%Creating the new figure
figure
%Plotting the columns of Y
plot(Y)
Plots each matrix column as a separate line
44. Plotting (contd.)
Combing multiple plots in single figure
using subplot
Syntax: subplot(NR,NC,Position number)
Where
NR: Number of Columns in figure
NC: Number of Columns in figure
Position: Position where this plot has to be shown