SlideShare a Scribd company logo
AM2032 JAYANTA MUKHERJEE
INTRODUCTION
TO
MATLAB
AM2032 JAYANTA MUKHERJEE
 Introduction to MATLAB
 Running MATLAB and MATLAB Environment
 Getting help
 Variables, Arithmetic and Logical Operators
 Matrices and Vectors
 Mathematical Functions
 Plotting
 Programming
 M-files
 User Defined Functions
 Miscellaneous
 Tips
AM2032 JAYANTA MUKHERJEE
Introduction to MATLAB
AM2032 JAYANTA MUKHERJEE
Running MATLAB &
the MATLAB
Environment
You can enter MATLAB
with system command
“matlab” , C:> matlab. Or,
it can be started by
clicking on the start-up
menu or a short-cut icon
AM2032 JAYANTA MUKHERJEE
MATLAB Desktop
Command
Window
Launch Pad
Command
History
After the “>>” symbol, you
can type the commands
Command History is
used to view previously
used functions, and
selected lines can be
copied and executed.
Launch Pad is used to
provide easy access to
tools, demos, and
documentation.
Command Window is
used to enter variables
and run functions and
M-files. The Command
window is where you
can interact with
Matlab directly. Default
working directory on
Windows is C:/
MATLAB / bin.
AM2032 JAYANTA MUKHERJEE
MATLAB Desktop – cont’d
Command
Window
Workspace
Current
Directory
Workspace
consists of the set of
variables (named arrays)
built up during a
MATLAB session and
stored in memory.
Current Directory
is used to change
directory that is
worked on, quickly.
AM2032 JAYANTA MUKHERJEE
MATLAB Editor
Access to
commands
Color keyed text with
auto indents
tabbed sheets for other
files being edited
AM2032 JAYANTA MUKHERJEE
Getting MATLAB Help
• Type one of the following
commands in the command
window:
>>help – lists all the help topics
>>help topic – provides help for the
specified topic
>>help command – provides help for the
specified command
>>helpwin – opens a separate help
window for navigation
>>Lookfor keyword – search all M-files
for keyword
• Online resource
AM2032 JAYANTA MUKHERJEE
MATLAB Variables
• The MATLAB environment is command oriented somewhat like UNIX.
A prompt appears on the screen and a MATLAB statement can be entered.
When the <ENTER> key is pressed, the statement is executed, and another
prompt appears.
• If a statement is terminated with a semicolon ( ; ), no results will be
displayed. Otherwise results will appear before the next prompt.
• Variable names ARE case sensitive.
• Variable names can contain up to 63 characters (as of MATLAB 6.5 and
newer).
• Variable names must start with a letter followed by letters, digits, and
underscores.
• Variable names and their types do not have to be declared in MATLAB.
• Any variable can take real, complex, and integer values.
• The name of variable is not accepted if it is reserved word.
AM2032 JAYANTA MUKHERJEE
MATLAB Variables – cont’d
• Special variables:
– ans: default variable name for the result.
– pi: π = 3.1415926 ……
– eps: ε= 2.2204e-016, smallest value by which two numbers can differ
– inf: ∞, infinity
– NAN or nan: not-a-number
• Commands involving variables:
– who: lists the names of the defined variables
– whos: lists the names and sizes of defined variables
– clear: clears all variables
– clear name: clears the variable name
– clc: clears the command window
– clf: clears the current figure and the graph window
– Ctrl+C: Aborts calculation
AM2032 JAYANTA MUKHERJEE
MATLAB Variables – cont’d
•You can think of computer memory as a large set of “boxes” in which
numbers can be stored. The values can be inspected and changed.
•Boxes can be labeled with a variable name.
>> A=3
A =
3
3
A
AM2032 JAYANTA MUKHERJEE
MATLAB Variables – cont’d
• Suppose we want to calculate the volume of a
cylinder.
• It’s radius and height are stored as variables in
memory.
>> volume = pi*radius^2*height
volume radius height
AM2032 JAYANTA MUKHERJEE
MATLAB Variables – cont’d
• Variable is a name given to a reserved
location in memory.
>>x = 111;
>>number_of_students = 75;
>>name = ‘University College Cork’;
>>radius = 5;
>>area = pi * radius^2;
>>x_value=23
x_value=23
AM2032 JAYANTA MUKHERJEE
MATLAB Arithmetic Operators
Operator Description
+ Addition
- Subtraction
.* Multiplication (element wise)
./ Right division (element wise)
. Left division (element wise)
= Assignment operator,e.g. a = b,(assign b to a)
: Colon operator (Specify Range )
.^ Power (element wise)
' Transpose
* Matrix multiplication
/ Matrix right division
 Matrix left division
; Row separator in a Matrix
^ Matrix power
AM2032 JAYANTA MUKHERJEE
Logical Operators
in MATLAB
Operator Description
& Returns 1 for every element location that is true (nonzero) in both arrays, and
0 for all other elements.
| Returns 1 for every element location that is true (nonzero) in either one or the
other, or both, arrays and 0 for all other elements.
~ Complements each element of input array, A.
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
AM2032 JAYANTA MUKHERJEE
Calculations at the Command
Line / Workspace
» -5/(4.8+5.32)^2
ans =
-0.0488
» (3+4i)*(3-4i)
ans =
25
» cos(pi/2)
ans =
6.1230e-017
» exp(acos(0.3))
ans =
3.5470
» a = 2;
» b = 5;
» a^b
ans =
32
» x = 5/2*pi;
» y = sin(x)
y =
1
» z = asin(y)
z =
1.5708
Results
assigned to
“ans” if name
not specified
() parentheses for
function inputs
Semicolon
suppresses
screen output
MATLAB as a calculator Assigning Variables
Copyright  1984 - 1998 by The MathWorks, Inc.
AM2032 JAYANTA MUKHERJEE
Vector & Matrix
in MATLAB
4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10
1
2
Rows (m) 3
4
5
Columns
(n)
1 2 3 4 5
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
A = A (2,4)
A (17)
Rectangular Matrix:
Scalar: 1-by-1 array
Vector: m-by-1 array
1-by-n array
Matrix: m-by-n array
Matrix elements can be EITHER
numbers OR characters
Copyright  1984 - 1998 by The MathWorks, Inc.
How do you specify this 5ⅹ 5 matrix ‘A’ in MATLAB ?
>>A=[4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10 ];
>>A=[4 10 1 6 2; 8 1.2 9 4 25; 7.2 5 7 1 11; 0 0.5 4 5 56; 23 83 13 0 10 ];
AM2032 JAYANTA MUKHERJEE
2 7 4
2
7
4
2 7 4
3 8 9
?
Examples (Vectors)
X=[2 7 4];
X=[2; 7; 4];
X=[2 7 4]’;
X=[2 7 4;3 8 9];
Y=[X X];
2 7 4
3 8 9
2 7 4
3 8 9
Row Vector
Column Vector
Matrix or a
2D array
Matrix
of
matrices
AM2032 JAYANTA MUKHERJEE
More on Vectors
x = start:end Creates row vector x starting with start, counting by 1 ,
ending at end
x = initial value : increment : final
value
Creates row vector x starting with start, counting by
increment, ending at or before end
x = linspace(start,end,number) Creates linearly spaced row vector x starting with start,
ending at end, having number elements
x = logspace(start,end,number) Creates logarithmically spaced row vector x starting
with start, ending with end, having number elements
length(x) Returns the length of vector x
y = x’ Transpose of vector x
dot(x,y),cross(x,y) Returns the scalar dot and vector cross product of the
vector x and y
AM2032 JAYANTA MUKHERJEE
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(m,n) Returns a m ⅹ n matrix of zeros
rand(m,n) Returns a m ⅹ n matrix of random numbers
eye(m,n) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(m,n) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A, returns the row vector [m,n]
containing the number of rows and columns in matrix
length(A) Returns the larger of the number of rows or columns in A
AM2032 JAYANTA MUKHERJEE
Any MATLAB expression can
be entered as a matrix element
Entering Numeric Arrays
» a=[1 2;3 4]
a =
1 2
3 4
» b=[-2.8, sqrt(-7), (3+5+6)*3/4]
b =
-2.8000 0 + 2.6458i 10.5000
» b(2,5) = 23
b =
-2.8000 0 + 2.6458i 10.5000 0 0
0 0 0 0 23.0000
Row separator:
semicolon (;)
Column separator:
space / comma (,)
Use square
brackets [ ]
Matrices must be rectangular/same
height. (Set undefined elements to zero)
Copyright  1984 - 1998 by The MathWorks, Inc.
MATLAB does not allow this !
AM2032 JAYANTA MUKHERJEE
Entering Numeric Arrays - cont.
» w=[1 2;3 4] + 5
w =
6 7
8 9
» x = 1:5
x =
1 2 3 4 5
» y = 2:-0.5:0
y =
2.0000 1.5000 1.0000 0.5000 0
» z = rand(2,4)
z =
0.9501 0.6068 0.8913 0.4565
0.2311 0.4860 0.7621 0.0185
Scalar expansion
Creating sequences
colon operator (:)
Utility functions for
creating matrices.
Copyright  1984 - 1998 by The MathWorks, Inc.
AM2032 JAYANTA MUKHERJEE
Numerical Array Concatenation - [ ]
» a=[1 2;3 4]
a =
1 2
3 4
» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use [ ] to combine
existing arrays as
matrix “elements”
Row separator:
semicolon (;)
Column separator:
space / comma (,)
Use square
brackets [ ]
The resulting
matrix must
be rectangular.
4*a
Copyright  1984 - 1998 by The MathWorks, Inc.
AM2032 JAYANTA MUKHERJEE
Array Subscripting / Indexing
4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10
1
2
3
4
5
1 2 3 4 5
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
A =
A(3,1)
A(3)
A(1:5,5)
A(:,5)
A(21:25)
A(4:5,2:3)
A([9 14;10 15])
• Use () parentheses to specify index
• colon operator (:) specifies range / ALL
• [ ] to create matrix of index subscripts
• ‘end’ specifies maximum index value
A(1:end,end)
A(:,end)
A(21:end)’
Copyright  1984 - 1998 by The MathWorks, Inc.
AM2032 JAYANTA MUKHERJEE
Some operations should be
handled with care
>>A=[1 2;4 5];
>>B=A*A % prints
9 12
24 33 % Proper matrix multiplication
>>
>>B=A.*A % prints
1 4
16 25 % Element by element multiplication
AM2032 JAYANTA MUKHERJEE
Operations on Matrices
Transpose B=A’
Identity Matrix
eye(n) -> returns an n X n identity matrix
eye(m,n) -> returns an m X n matrix with ones on the
main diagonal and zeros elsewhere
Addition and Subtraction C =A +B C =A - B
Scalar Multiplication B = α A, where α is a scalar
Matrix Multiplication C = A * B
Matrix Inverse B = inv(A), A must be a square matrix in this case
Matrix powers B = A * A , A must be a square matrix
Determinant det(A), A must be a square matrix
AM2032 JAYANTA MUKHERJEE
Multidimensional Arrays
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
» A = Pascal(4);
» A(:,:,2) = magic(4)
A(:,:,1)
1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20
A(:,:,2)
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
» A(:,:,9) = diag(ones(1,4));
Page N
Page 1
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20
>>A = 1;
while length(A) < 4
A = [0 A] + [A 0];
end
AM2032 JAYANTA MUKHERJEE
Operating on Matrices
AM2032 JAYANTA MUKHERJEE
Operating on Matrices - cont.
• Matrices must have the same dimensions
• Dimensions of resulting matrix = dimensions of
multiplied matrices
• Resulting elements = product of corresponding
elements from the original matrices
Array Multiplication
» a = [1 2 3 4; 5 6 7 8];
» b = [1:4; 1:4];
» c = a.*b
c =
1 4 9 16
5 12 21 32 c(2,4) = a(2,4)*b(2,4)
Same rules apply for other
array operations too !
AM2032 JAYANTA MUKHERJEE
String Arrays
• Created using single quote delimiter (')
• Each character is a separate matrix element
(16 bits of memory per character)
» str = 'Hi there,'
str =
Hi there,
» str2 = 'Isn't MATLAB great?'
str2 =
Isn't MATLAB great?
1x9 vector
str = H i t h e r e ,
AM2032 JAYANTA MUKHERJEE
Mathematical Functions of MATLAB-1
Elemantary Mathematical (Trigonometric) Functions
Trigonometric
functions
Remarks
sin(x)
cos(x)
tan(x)
asin(x)
acos(x)
atan(x)
atan2(y,x)
sinh(x)
cosh(x)
tanh(x)
asinh(x)
acosh(x)
atanh(x)
- pi/2 ≤ atan(x) ≥ pi/2, Same as atan(y/x) but –pi ≥ atan(y,x) ≥ pi
AM2032 JAYANTA MUKHERJEE
Other elemantary
functions
Remarks
abs(x)
angle(x)
sqrt(x)
real(x)
imag(x)
conj(x)
round(x)
fix(x)
floor(x)
ceil(x)
sign(x)
exp(x)
log(x)
log10(x)
factor(x)
Absolute value of x
Phase angle of complex value: If x = real, angle = 0. If x = √-1, angle =
pi/2
Square root of x
Real part of complex value x
Imaginary part of complex value x
Complex conjugate x
Round to do nearest integer
Round a real value toward zero
Round x toward - ∞
Round x toward + ∞
+1 if x > 0; -1 if x < 0
Exponential base e
Log base e
Log base 10
1 if x is a prime number, 0 if not
Mathematical Functions of MATLAB-2
And there are many many more !
AM2032 JAYANTA MUKHERJEE
Plotting in MATLAB
• Specify x-data and/or y-data
• Specify color, line style and marker symbol
• Syntax: 2-D Plotting
– Plotting single line:
– Plotting multiple lines:
plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)
plot(xdata, ydata, 'color_linestyle_marker')
AM2032 JAYANTA MUKHERJEE
2-D Plotting - example
Create a Blue
(default color)
Sine Wave
» x = 0:1:2*pi;
» y = sin(x);
» plot(x,y);
AM2032 JAYANTA MUKHERJEE
2-D Plotting : example-cont.
• GRID ON creates a
grid on the current
figure
• GRID OFF turns off
the grid from the
current figure
• GRID toggles the grid
state
» x = 0:1:2*pi;
» y = sin(x);
» plot(x,y);grid on;
Adding a Grid
AM2032 JAYANTA MUKHERJEE
Adding additional plots to a
figure
• HOLD ON holds the
current plot
• HOLD OFF releases
hold on current plot
• HOLD toggles the
hold state
» x = 0:.1:2*pi;
» y = sin(x);
» plot(x,y,'b')
» grid on;
» hold on;
» plot(x,exp(-x),'r:*');
AM2032 JAYANTA MUKHERJEE
Controlling Viewing Area
• ZOOM ON allows user
to select viewing area
• ZOOM OFF prevents
zooming operations
• ZOOM toggles the
zoom state
• AXIS sets axis range
[xmin xmax ymin ymax]
» axis([0 2*pi 0 1]);
AM2032 JAYANTA MUKHERJEE
Graph Annotation
TITLE
TEXT
or
GTEXT
XLABEL
YLABEL
LEGEND
AM2032 JAYANTA MUKHERJEE
Subplots
SUBPLOT- display multiple axes in the same figure window
»subplot(2,2,1);
»plot(1:10);
»subplot(2,2,2);
»x = 0:.1:2*pi;
»plot(x,sin(x));
»subplot(2,2,3);
»x = 0:.1:2*pi;
»plot(x,exp(-x),’r’);
»subplot(2,2,4);
»plot(peaks);
subplot(#rows, #cols, index);
AM2032 JAYANTA MUKHERJEE
Alternative Scales for Axes
SEMILOGY
log Y
linear X
PLOTYY
2 sets of
linear axes
LOGLOG
Both axes
logarithmic
SEMILOGX
log X
linear Y
AM2032 JAYANTA MUKHERJEE
3-D Line Plotting
» z = 0:0.1:40;
» x = cos(z);
» y = sin(z);
» plot3(x,y,z);grid on;
plot3(xdata, ydata, zdata, 'clm', ...)
AM2032 JAYANTA MUKHERJEE
3-D Surface Plotting
AM2032 JAYANTA MUKHERJEE
Example:Advanced 3-D Plotting
» B = -0.2;
» x = 0:0.1:2*pi;
» y = -pi/2:0.1:pi/2;
» [x,y] = meshgrid(x,y);
» z = exp(B*x).*sin(x).*cos(y);
» surf(x,y,z)
AM2032 JAYANTA MUKHERJEE
Next Lecture: Programming with
Matlab
Lecture notes can be found at the following link:
http://euclid.ucc.ie/framesets/fset_staffdirectory.htm
Then click on my name and then on Lecture Notes
AM2032 JAYANTA MUKHERJEE
Questions?

More Related Content

Similar to Matlab an Introduction_Lecture_for all.ppt (20)

PPT
Matlab Tutorial.ppt
RaviMuthamala1
 
PPTX
intro2matlab-basic knowledge about Matlab.pptx
uf5221985
 
PPT
Brief Introduction to Matlab
Tariq kanher
 
PPTX
Matlab-1.pptx
aboma2hawi
 
PPTX
matlab
Farhan Ahmed
 
PPT
Matlab introduction
Vikash Jakhar
 
PPT
Matlab introduction
Satish Gummadi
 
PDF
Matlab Tutorial for Beginners - I
Vijay Kumar Gupta
 
PPTX
MATLAB for Engineers ME1006 (1 for beginer).pptx
lav8bell
 
PPTX
An Introduction to MATLAB for beginners
Murshida ck
 
PDF
lecture #1 & 2....education....matlab...helpful
AiveerKhan
 
DOCX
MATLAB guide
Prerna Rathore
 
PDF
Basics of programming in matlab for beginners
opiophillip
 
PDF
MATLAB INTRODUCTION
Dr. Krishna Mohbey
 
PPTX
Matlab ppt
chestialtaff
 
PDF
Matlabch01
Mohammad Ayyash
 
PPTX
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
prashantkumarchinama
 
PPT
Matlab anilkumar
THEMASTERBLASTERSVID
 
PPT
Introduction to matlab
Mohammad Tawfik
 
Matlab Tutorial.ppt
RaviMuthamala1
 
intro2matlab-basic knowledge about Matlab.pptx
uf5221985
 
Brief Introduction to Matlab
Tariq kanher
 
Matlab-1.pptx
aboma2hawi
 
matlab
Farhan Ahmed
 
Matlab introduction
Vikash Jakhar
 
Matlab introduction
Satish Gummadi
 
Matlab Tutorial for Beginners - I
Vijay Kumar Gupta
 
MATLAB for Engineers ME1006 (1 for beginer).pptx
lav8bell
 
An Introduction to MATLAB for beginners
Murshida ck
 
lecture #1 & 2....education....matlab...helpful
AiveerKhan
 
MATLAB guide
Prerna Rathore
 
Basics of programming in matlab for beginners
opiophillip
 
MATLAB INTRODUCTION
Dr. Krishna Mohbey
 
Matlab ppt
chestialtaff
 
Matlabch01
Mohammad Ayyash
 
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
prashantkumarchinama
 
Matlab anilkumar
THEMASTERBLASTERSVID
 
Introduction to matlab
Mohammad Tawfik
 

Recently uploaded (20)

PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Horarios de distribución de agua en julio
pegazohn1978
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Ad

Matlab an Introduction_Lecture_for all.ppt

  • 2. AM2032 JAYANTA MUKHERJEE  Introduction to MATLAB  Running MATLAB and MATLAB Environment  Getting help  Variables, Arithmetic and Logical Operators  Matrices and Vectors  Mathematical Functions  Plotting  Programming  M-files  User Defined Functions  Miscellaneous  Tips
  • 4. AM2032 JAYANTA MUKHERJEE Running MATLAB & the MATLAB Environment You can enter MATLAB with system command “matlab” , C:> matlab. Or, it can be started by clicking on the start-up menu or a short-cut icon
  • 5. AM2032 JAYANTA MUKHERJEE MATLAB Desktop Command Window Launch Pad Command History After the “>>” symbol, you can type the commands Command History is used to view previously used functions, and selected lines can be copied and executed. Launch Pad is used to provide easy access to tools, demos, and documentation. Command Window is used to enter variables and run functions and M-files. The Command window is where you can interact with Matlab directly. Default working directory on Windows is C:/ MATLAB / bin.
  • 6. AM2032 JAYANTA MUKHERJEE MATLAB Desktop – cont’d Command Window Workspace Current Directory Workspace consists of the set of variables (named arrays) built up during a MATLAB session and stored in memory. Current Directory is used to change directory that is worked on, quickly.
  • 7. AM2032 JAYANTA MUKHERJEE MATLAB Editor Access to commands Color keyed text with auto indents tabbed sheets for other files being edited
  • 8. AM2032 JAYANTA MUKHERJEE Getting MATLAB Help • Type one of the following commands in the command window: >>help – lists all the help topics >>help topic – provides help for the specified topic >>help command – provides help for the specified command >>helpwin – opens a separate help window for navigation >>Lookfor keyword – search all M-files for keyword • Online resource
  • 9. AM2032 JAYANTA MUKHERJEE MATLAB Variables • The MATLAB environment is command oriented somewhat like UNIX. A prompt appears on the screen and a MATLAB statement can be entered. When the <ENTER> key is pressed, the statement is executed, and another prompt appears. • If a statement is terminated with a semicolon ( ; ), no results will be displayed. Otherwise results will appear before the next prompt. • Variable names ARE case sensitive. • Variable names can contain up to 63 characters (as of MATLAB 6.5 and newer). • Variable names must start with a letter followed by letters, digits, and underscores. • Variable names and their types do not have to be declared in MATLAB. • Any variable can take real, complex, and integer values. • The name of variable is not accepted if it is reserved word.
  • 10. AM2032 JAYANTA MUKHERJEE MATLAB Variables – cont’d • Special variables: – ans: default variable name for the result. – pi: π = 3.1415926 …… – eps: ε= 2.2204e-016, smallest value by which two numbers can differ – inf: ∞, infinity – NAN or nan: not-a-number • Commands involving variables: – who: lists the names of the defined variables – whos: lists the names and sizes of defined variables – clear: clears all variables – clear name: clears the variable name – clc: clears the command window – clf: clears the current figure and the graph window – Ctrl+C: Aborts calculation
  • 11. AM2032 JAYANTA MUKHERJEE MATLAB Variables – cont’d •You can think of computer memory as a large set of “boxes” in which numbers can be stored. The values can be inspected and changed. •Boxes can be labeled with a variable name. >> A=3 A = 3 3 A
  • 12. AM2032 JAYANTA MUKHERJEE MATLAB Variables – cont’d • Suppose we want to calculate the volume of a cylinder. • It’s radius and height are stored as variables in memory. >> volume = pi*radius^2*height volume radius height
  • 13. AM2032 JAYANTA MUKHERJEE MATLAB Variables – cont’d • Variable is a name given to a reserved location in memory. >>x = 111; >>number_of_students = 75; >>name = ‘University College Cork’; >>radius = 5; >>area = pi * radius^2; >>x_value=23 x_value=23
  • 14. AM2032 JAYANTA MUKHERJEE MATLAB Arithmetic Operators Operator Description + Addition - Subtraction .* Multiplication (element wise) ./ Right division (element wise) . Left division (element wise) = Assignment operator,e.g. a = b,(assign b to a) : Colon operator (Specify Range ) .^ Power (element wise) ' Transpose * Matrix multiplication / Matrix right division Matrix left division ; Row separator in a Matrix ^ Matrix power
  • 15. AM2032 JAYANTA MUKHERJEE Logical Operators in MATLAB Operator Description & Returns 1 for every element location that is true (nonzero) in both arrays, and 0 for all other elements. | Returns 1 for every element location that is true (nonzero) in either one or the other, or both, arrays and 0 for all other elements. ~ Complements each element of input array, A. < Less than <= Less than or equal to > Greater than >= Greater than or equal to == Equal to ~= Not equal to
  • 16. AM2032 JAYANTA MUKHERJEE Calculations at the Command Line / Workspace » -5/(4.8+5.32)^2 ans = -0.0488 » (3+4i)*(3-4i) ans = 25 » cos(pi/2) ans = 6.1230e-017 » exp(acos(0.3)) ans = 3.5470 » a = 2; » b = 5; » a^b ans = 32 » x = 5/2*pi; » y = sin(x) y = 1 » z = asin(y) z = 1.5708 Results assigned to “ans” if name not specified () parentheses for function inputs Semicolon suppresses screen output MATLAB as a calculator Assigning Variables Copyright  1984 - 1998 by The MathWorks, Inc.
  • 17. AM2032 JAYANTA MUKHERJEE Vector & Matrix in MATLAB 4 10 1 6 2 8 1.2 9 4 25 7.2 5 7 1 11 0 0.5 4 5 56 23 83 13 0 10 1 2 Rows (m) 3 4 5 Columns (n) 1 2 3 4 5 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25 A = A (2,4) A (17) Rectangular Matrix: Scalar: 1-by-1 array Vector: m-by-1 array 1-by-n array Matrix: m-by-n array Matrix elements can be EITHER numbers OR characters Copyright  1984 - 1998 by The MathWorks, Inc. How do you specify this 5ⅹ 5 matrix ‘A’ in MATLAB ? >>A=[4 10 1 6 2 8 1.2 9 4 25 7.2 5 7 1 11 0 0.5 4 5 56 23 83 13 0 10 ]; >>A=[4 10 1 6 2; 8 1.2 9 4 25; 7.2 5 7 1 11; 0 0.5 4 5 56; 23 83 13 0 10 ];
  • 18. AM2032 JAYANTA MUKHERJEE 2 7 4 2 7 4 2 7 4 3 8 9 ? Examples (Vectors) X=[2 7 4]; X=[2; 7; 4]; X=[2 7 4]’; X=[2 7 4;3 8 9]; Y=[X X]; 2 7 4 3 8 9 2 7 4 3 8 9 Row Vector Column Vector Matrix or a 2D array Matrix of matrices
  • 19. AM2032 JAYANTA MUKHERJEE More on Vectors x = start:end Creates row vector x starting with start, counting by 1 , ending at end x = initial value : increment : final value Creates row vector x starting with start, counting by increment, ending at or before end x = linspace(start,end,number) Creates linearly spaced row vector x starting with start, ending at end, having number elements x = logspace(start,end,number) Creates logarithmically spaced row vector x starting with start, ending with end, having number elements length(x) Returns the length of vector x y = x’ Transpose of vector x dot(x,y),cross(x,y) Returns the scalar dot and vector cross product of the vector x and y
  • 20. AM2032 JAYANTA MUKHERJEE More on Matrices zeros(n) Returns a n ⅹ n matrix of zeros zeros(m,n) Returns a m ⅹ n matrix of zeros rand(m,n) Returns a m ⅹ n matrix of random numbers eye(m,n) Returns a m ⅹ n Identity matrix ones(n) Returns a n ⅹ n matrix of ones ones(m,n) Returns a m ⅹ n matrix of ones size(A) For a m ⅹ n matrix A, returns the row vector [m,n] containing the number of rows and columns in matrix length(A) Returns the larger of the number of rows or columns in A
  • 21. AM2032 JAYANTA MUKHERJEE Any MATLAB expression can be entered as a matrix element Entering Numeric Arrays » a=[1 2;3 4] a = 1 2 3 4 » b=[-2.8, sqrt(-7), (3+5+6)*3/4] b = -2.8000 0 + 2.6458i 10.5000 » b(2,5) = 23 b = -2.8000 0 + 2.6458i 10.5000 0 0 0 0 0 0 23.0000 Row separator: semicolon (;) Column separator: space / comma (,) Use square brackets [ ] Matrices must be rectangular/same height. (Set undefined elements to zero) Copyright  1984 - 1998 by The MathWorks, Inc. MATLAB does not allow this !
  • 22. AM2032 JAYANTA MUKHERJEE Entering Numeric Arrays - cont. » w=[1 2;3 4] + 5 w = 6 7 8 9 » x = 1:5 x = 1 2 3 4 5 » y = 2:-0.5:0 y = 2.0000 1.5000 1.0000 0.5000 0 » z = rand(2,4) z = 0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185 Scalar expansion Creating sequences colon operator (:) Utility functions for creating matrices. Copyright  1984 - 1998 by The MathWorks, Inc.
  • 23. AM2032 JAYANTA MUKHERJEE Numerical Array Concatenation - [ ] » a=[1 2;3 4] a = 1 2 3 4 » cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24 Use [ ] to combine existing arrays as matrix “elements” Row separator: semicolon (;) Column separator: space / comma (,) Use square brackets [ ] The resulting matrix must be rectangular. 4*a Copyright  1984 - 1998 by The MathWorks, Inc.
  • 24. AM2032 JAYANTA MUKHERJEE Array Subscripting / Indexing 4 10 1 6 2 8 1.2 9 4 25 7.2 5 7 1 11 0 0.5 4 5 56 23 83 13 0 10 1 2 3 4 5 1 2 3 4 5 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25 A = A(3,1) A(3) A(1:5,5) A(:,5) A(21:25) A(4:5,2:3) A([9 14;10 15]) • Use () parentheses to specify index • colon operator (:) specifies range / ALL • [ ] to create matrix of index subscripts • ‘end’ specifies maximum index value A(1:end,end) A(:,end) A(21:end)’ Copyright  1984 - 1998 by The MathWorks, Inc.
  • 25. AM2032 JAYANTA MUKHERJEE Some operations should be handled with care >>A=[1 2;4 5]; >>B=A*A % prints 9 12 24 33 % Proper matrix multiplication >> >>B=A.*A % prints 1 4 16 25 % Element by element multiplication
  • 26. AM2032 JAYANTA MUKHERJEE Operations on Matrices Transpose B=A’ Identity Matrix eye(n) -> returns an n X n identity matrix eye(m,n) -> returns an m X n matrix with ones on the main diagonal and zeros elsewhere Addition and Subtraction C =A +B C =A - B Scalar Multiplication B = α A, where α is a scalar Matrix Multiplication C = A * B Matrix Inverse B = inv(A), A must be a square matrix in this case Matrix powers B = A * A , A must be a square matrix Determinant det(A), A must be a square matrix
  • 27. AM2032 JAYANTA MUKHERJEE Multidimensional Arrays 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 » A = Pascal(4); » A(:,:,2) = magic(4) A(:,:,1) 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 20 A(:,:,2) 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1 » A(:,:,9) = diag(ones(1,4)); Page N Page 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 20 >>A = 1; while length(A) < 4 A = [0 A] + [A 0]; end
  • 29. AM2032 JAYANTA MUKHERJEE Operating on Matrices - cont. • Matrices must have the same dimensions • Dimensions of resulting matrix = dimensions of multiplied matrices • Resulting elements = product of corresponding elements from the original matrices Array Multiplication » a = [1 2 3 4; 5 6 7 8]; » b = [1:4; 1:4]; » c = a.*b c = 1 4 9 16 5 12 21 32 c(2,4) = a(2,4)*b(2,4) Same rules apply for other array operations too !
  • 30. AM2032 JAYANTA MUKHERJEE String Arrays • Created using single quote delimiter (') • Each character is a separate matrix element (16 bits of memory per character) » str = 'Hi there,' str = Hi there, » str2 = 'Isn't MATLAB great?' str2 = Isn't MATLAB great? 1x9 vector str = H i t h e r e ,
  • 31. AM2032 JAYANTA MUKHERJEE Mathematical Functions of MATLAB-1 Elemantary Mathematical (Trigonometric) Functions Trigonometric functions Remarks sin(x) cos(x) tan(x) asin(x) acos(x) atan(x) atan2(y,x) sinh(x) cosh(x) tanh(x) asinh(x) acosh(x) atanh(x) - pi/2 ≤ atan(x) ≥ pi/2, Same as atan(y/x) but –pi ≥ atan(y,x) ≥ pi
  • 32. AM2032 JAYANTA MUKHERJEE Other elemantary functions Remarks abs(x) angle(x) sqrt(x) real(x) imag(x) conj(x) round(x) fix(x) floor(x) ceil(x) sign(x) exp(x) log(x) log10(x) factor(x) Absolute value of x Phase angle of complex value: If x = real, angle = 0. If x = √-1, angle = pi/2 Square root of x Real part of complex value x Imaginary part of complex value x Complex conjugate x Round to do nearest integer Round a real value toward zero Round x toward - ∞ Round x toward + ∞ +1 if x > 0; -1 if x < 0 Exponential base e Log base e Log base 10 1 if x is a prime number, 0 if not Mathematical Functions of MATLAB-2 And there are many many more !
  • 33. AM2032 JAYANTA MUKHERJEE Plotting in MATLAB • Specify x-data and/or y-data • Specify color, line style and marker symbol • Syntax: 2-D Plotting – Plotting single line: – Plotting multiple lines: plot(x1, y1, 'clm1', x2, y2, 'clm2', ...) plot(xdata, ydata, 'color_linestyle_marker')
  • 34. AM2032 JAYANTA MUKHERJEE 2-D Plotting - example Create a Blue (default color) Sine Wave » x = 0:1:2*pi; » y = sin(x); » plot(x,y);
  • 35. AM2032 JAYANTA MUKHERJEE 2-D Plotting : example-cont. • GRID ON creates a grid on the current figure • GRID OFF turns off the grid from the current figure • GRID toggles the grid state » x = 0:1:2*pi; » y = sin(x); » plot(x,y);grid on; Adding a Grid
  • 36. AM2032 JAYANTA MUKHERJEE Adding additional plots to a figure • HOLD ON holds the current plot • HOLD OFF releases hold on current plot • HOLD toggles the hold state » x = 0:.1:2*pi; » y = sin(x); » plot(x,y,'b') » grid on; » hold on; » plot(x,exp(-x),'r:*');
  • 37. AM2032 JAYANTA MUKHERJEE Controlling Viewing Area • ZOOM ON allows user to select viewing area • ZOOM OFF prevents zooming operations • ZOOM toggles the zoom state • AXIS sets axis range [xmin xmax ymin ymax] » axis([0 2*pi 0 1]);
  • 38. AM2032 JAYANTA MUKHERJEE Graph Annotation TITLE TEXT or GTEXT XLABEL YLABEL LEGEND
  • 39. AM2032 JAYANTA MUKHERJEE Subplots SUBPLOT- display multiple axes in the same figure window »subplot(2,2,1); »plot(1:10); »subplot(2,2,2); »x = 0:.1:2*pi; »plot(x,sin(x)); »subplot(2,2,3); »x = 0:.1:2*pi; »plot(x,exp(-x),’r’); »subplot(2,2,4); »plot(peaks); subplot(#rows, #cols, index);
  • 40. AM2032 JAYANTA MUKHERJEE Alternative Scales for Axes SEMILOGY log Y linear X PLOTYY 2 sets of linear axes LOGLOG Both axes logarithmic SEMILOGX log X linear Y
  • 41. AM2032 JAYANTA MUKHERJEE 3-D Line Plotting » z = 0:0.1:40; » x = cos(z); » y = sin(z); » plot3(x,y,z);grid on; plot3(xdata, ydata, zdata, 'clm', ...)
  • 42. AM2032 JAYANTA MUKHERJEE 3-D Surface Plotting
  • 43. AM2032 JAYANTA MUKHERJEE Example:Advanced 3-D Plotting » B = -0.2; » x = 0:0.1:2*pi; » y = -pi/2:0.1:pi/2; » [x,y] = meshgrid(x,y); » z = exp(B*x).*sin(x).*cos(y); » surf(x,y,z)
  • 44. AM2032 JAYANTA MUKHERJEE Next Lecture: Programming with Matlab Lecture notes can be found at the following link: http://euclid.ucc.ie/framesets/fset_staffdirectory.htm Then click on my name and then on Lecture Notes