SlideShare a Scribd company logo
INTRODUCTION TO MATLAB
PROGRAMMING
PRESENTED BY
DR. VIKRAM MUTNEJA,
ASSOCIATE PROFESSOR,
SHAHEED BHAGAT SINGH STATE
UNIVERSITY
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
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
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
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
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
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
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
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
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
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
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
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
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
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’);
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
Writing Loops
 While loop
 Syntax
while(logical expression)
loop body..
.....
end
 Example
i=10;
while(i<30)
disp(i);
i=i+1;
end
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
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
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
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.
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
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
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
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
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
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
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
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
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
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
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
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
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.
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
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)
Plotting (contd.)
 Output
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’);
Plotting (contd.)
 Output
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)
Plotting (contd.)
 Output
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
Plotting (contd.)
 Output
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
Plotting (contd.)
 Sample Output
That is all for now...
 Thanks
 Any Queries Please

More Related Content

DOCX
MATLAB BASICS
PPTX
Matlab for diploma students(1)
PPT
Matlab intro
PPT
Introduction to Matlab
PPT
Matlab anilkumar
PPTX
Basic of Python- Hands on Session
PPT
Basics of programming in matlab
PPT
Introduction to MatLab programming
MATLAB BASICS
Matlab for diploma students(1)
Matlab intro
Introduction to Matlab
Matlab anilkumar
Basic of Python- Hands on Session
Basics of programming in matlab
Introduction to MatLab programming

What's hot (20)

PDF
Matlab commands
PPTX
Matlab
PPT
Matlab1
PPTX
Seminar on MATLAB
PPTX
MATLAB - The Need to Know Basics
PPT
Introduction to matlab
PPT
Brief Introduction to Matlab
PPT
Matlab Overviiew
PPT
Introduction to matlab
PPTX
Matlab Workshop Presentation
PDF
MATLAB Programming
PPT
Learn Matlab
PPTX
Matlab ppt
PDF
A complete introduction on matlab and matlab's projects
PPT
Matlab tme series benni
PDF
Matlab intro
PDF
Matlab intro
PDF
MATLAB INTRODUCTION
Matlab commands
Matlab
Matlab1
Seminar on MATLAB
MATLAB - The Need to Know Basics
Introduction to matlab
Brief Introduction to Matlab
Matlab Overviiew
Introduction to matlab
Matlab Workshop Presentation
MATLAB Programming
Learn Matlab
Matlab ppt
A complete introduction on matlab and matlab's projects
Matlab tme series benni
Matlab intro
Matlab intro
MATLAB INTRODUCTION
Ad

Similar to Introduction to matlab (20)

PPTX
From zero to MATLAB hero: Mastering the basics and beyond
PDF
PDF
lecture #1 & 2....education....matlab...helpful
PDF
Matlab guide
DOCX
Signals And Systems Lab Manual, R18 Batch
PDF
Dsp lab _eec-652__vi_sem_18012013
PDF
Dsp lab _eec-652__vi_sem_18012013
PDF
interfacing matlab with embedded systems
PPT
WIDI ediot autis dongok part 3.EDIOT LU LEMBOT LY
PPT
WIDI ediot autis dongok part 2.ediot lu lembot lu
PDF
EE6711 Power System Simulation Lab manual
PPT
WIDI FREAK MANUSIA SETENGAH EDIOTDAN LEMBOT
PPTX
3_MATLAB Basics Introduction for Engineers .pptx
PPT
WIDI ediot autis dongok part 1.ediot lu lemot lu setan lu
PPT
MatlabIntro (1).ppt
DOCX
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
PPT
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
PPT
MatlabIntro1234.ppt.....................
DOCX
KEVIN MERCHANT DOCUMENT
DOCX
Kevin merchantss
From zero to MATLAB hero: Mastering the basics and beyond
lecture #1 & 2....education....matlab...helpful
Matlab guide
Signals And Systems Lab Manual, R18 Batch
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
interfacing matlab with embedded systems
WIDI ediot autis dongok part 3.EDIOT LU LEMBOT LY
WIDI ediot autis dongok part 2.ediot lu lembot lu
EE6711 Power System Simulation Lab manual
WIDI FREAK MANUSIA SETENGAH EDIOTDAN LEMBOT
3_MATLAB Basics Introduction for Engineers .pptx
WIDI ediot autis dongok part 1.ediot lu lemot lu setan lu
MatlabIntro (1).ppt
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MatlabIntro1234.ppt.....................
KEVIN MERCHANT DOCUMENT
Kevin merchantss
Ad

Recently uploaded (20)

PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PPTX
web development for engineering and engineering
PPTX
additive manufacturing of ss316l using mig welding
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
PPT on Performance Review to get promotions
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Construction Project Organization Group 2.pptx
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Digital Logic Computer Design lecture notes
PPTX
Welding lecture in detail for understanding
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
Well-logging-methods_new................
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Strings in CPP - Strings in C++ are sequences of characters used to store and...
web development for engineering and engineering
additive manufacturing of ss316l using mig welding
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Lesson 3_Tessellation.pptx finite Mathematics
Lecture Notes Electrical Wiring System Components
OOP with Java - Java Introduction (Basics)
Internet of Things (IOT) - A guide to understanding
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPT on Performance Review to get promotions
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Construction Project Organization Group 2.pptx
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Digital Logic Computer Design lecture notes
Welding lecture in detail for understanding
Embodied AI: Ushering in the Next Era of Intelligent Systems
Well-logging-methods_new................
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT

Introduction to matlab

  • 1. INTRODUCTION TO MATLAB PROGRAMMING PRESENTED BY DR. VIKRAM MUTNEJA, ASSOCIATE PROFESSOR, SHAHEED BHAGAT SINGH STATE UNIVERSITY
  • 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
  • 46. That is all for now...  Thanks  Any Queries Please