SlideShare ist ein Scribd-Unternehmen logo
1 von 46
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

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Matlab commands
Matlab commandsMatlab commands
Matlab commands
 
Matlab
MatlabMatlab
Matlab
 
Matlab1
Matlab1Matlab1
Matlab1
 
Seminar on MATLAB
Seminar on MATLABSeminar on MATLAB
Seminar on MATLAB
 
MATLAB - The Need to Know Basics
MATLAB - The Need to Know BasicsMATLAB - The Need to Know Basics
MATLAB - The Need to Know Basics
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Brief Introduction to Matlab
Brief  Introduction to MatlabBrief  Introduction to Matlab
Brief Introduction to Matlab
 
Matlab Overviiew
Matlab OverviiewMatlab Overviiew
Matlab Overviiew
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Matlab Workshop Presentation
Matlab Workshop PresentationMatlab Workshop Presentation
Matlab Workshop Presentation
 
Matlab Manual
Matlab ManualMatlab Manual
Matlab Manual
 
Matlab
MatlabMatlab
Matlab
 
MATLAB Programming
MATLAB Programming MATLAB Programming
MATLAB Programming
 
Learn Matlab
Learn MatlabLearn Matlab
Learn Matlab
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsA complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projects
 
Matlab tme series benni
Matlab tme series benniMatlab tme series benni
Matlab tme series benni
 
Matlab intro
Matlab introMatlab intro
Matlab intro
 
Matlab intro
Matlab introMatlab intro
Matlab intro
 
MATLAB INTRODUCTION
MATLAB INTRODUCTIONMATLAB INTRODUCTION
MATLAB INTRODUCTION
 

Ähnlich wie Introduction to matlab

From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondFrom zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondMahuaPal6
 
Signals And Systems Lab Manual, R18 Batch
Signals And Systems Lab Manual, R18 BatchSignals And Systems Lab Manual, R18 Batch
Signals And Systems Lab Manual, R18 BatchAmairullah Khan Lodhi
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013amanabr
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Kurmendra Singh
 
interfacing matlab with embedded systems
interfacing matlab with embedded systemsinterfacing matlab with embedded systems
interfacing matlab with embedded systemsRaghav Shetty
 
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docxMATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docxandreecapon
 
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulinkMATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulinkreddyprasad reddyvari
 
Kevin merchantss
Kevin merchantssKevin merchantss
Kevin merchantssdharmesh69
 
KEVIN MERCHANT DOCUMENT
KEVIN MERCHANT DOCUMENTKEVIN MERCHANT DOCUMENT
KEVIN MERCHANT DOCUMENTtejas1235
 

Ähnlich wie Introduction to matlab (20)

From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondFrom zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyond
 
Ch1
Ch1Ch1
Ch1
 
Matlab guide
Matlab guideMatlab guide
Matlab guide
 
Signals And Systems Lab Manual, R18 Batch
Signals And Systems Lab Manual, R18 BatchSignals And Systems Lab Manual, R18 Batch
Signals And Systems Lab Manual, R18 Batch
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
interfacing matlab with embedded systems
interfacing matlab with embedded systemsinterfacing matlab with embedded systems
interfacing matlab with embedded systems
 
EE6711 Power System Simulation Lab manual
EE6711 Power System Simulation Lab manualEE6711 Power System Simulation Lab manual
EE6711 Power System Simulation Lab manual
 
MatlabIntro (1).ppt
MatlabIntro (1).pptMatlabIntro (1).ppt
MatlabIntro (1).ppt
 
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docxMATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
 
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulinkMATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
 
Kevin merchantss
Kevin merchantssKevin merchantss
Kevin merchantss
 
KEVIN MERCHANT DOCUMENT
KEVIN MERCHANT DOCUMENTKEVIN MERCHANT DOCUMENT
KEVIN MERCHANT DOCUMENT
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
Mmc manual
Mmc manualMmc manual
Mmc manual
 

Kürzlich hochgeladen

Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...soginsider
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfRagavanV2
 

Kürzlich hochgeladen (20)

Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 

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