MATLAB Unit 2 Study Material
MATLAB Unit 2 Study Material
Script Files:
7
-Example aa Scafptfile:
write a script file to solve the follousing Sstem
inear £quatioms:
2Y 2
3 2Y-1
2 r-1
or Ax=b.
windon)
typing the above Profi=m £dior and
In
After
Soving it, he execute the Sript in MATLAB.
T t s as follaWS
-
Tn the comm and indO) Eype;-
S> clear all clear the HOdkSpace
specity a Value of r
Solvex
Execute the eript file sdveX»m
det-A =
O: 2344
1.6815
Examples
Function befniton Line Fle Name,
fun ction [rho, HF] motion (XY,t) = motioN)
-Ote;
The first sod in the funchior definitian line, functian
must be typed in loercase.
X blah;
Body
funtionLY= moreblah.
N U
-1
L
U U N
-Prom 'the protim, it is tu be Noted that, i and det-A
are loal Variables.
- O0312
O2344
1 6815
>Who
-Debugging is the
ProcesS by
code.
or
in Your PYOgram £rrors can be
tNO Kind
Debuggin procesS,
The
COTrected.
Run-time £yrors,
Er rors and di)
() Syntax
the P r c e s s
are knad as bu9S, and
E r o r s in proorams debugging
is Knon a5
and eiminating them
locanin
MATLAE Tncludes a secial debugging tool called 2 Symbaic
debugger.
-This tool is émbedded. nto the EdiE/Debug indow.
execuion sthe
Using the SymbAlc dehEr tool, the
PYOWam s Checked Ome stateement at a time.
The M-fies tn The fbllsoinf Ways
- He can abo debuf
Edltor/Deblugger
the windaw
(b Usin The
COmmbnd
debug39ing
fnChons Om
d Osing in MATLAB.
Debusin
tWO-methols
Above are the
Debugging Tols:
-MATLAB SUPPOts a bullt-tn debuTqer
It Consists o everal debluggtng Commands. Some them are
Asted beloo:
dhclear, dbcont, dbdovn, dhult, dbstack, dbstatus, dhtep,
dbetop, dbtype , dbuP, etc
The above Command can be Uses to debg yo MATtLAR
Proranms
These Commands Can be Hritten in fhe M-file that younant
to debug
- the, Yoe can ue them dreiy yclickhg m them i the
flltolebeper indon.
-For dedaiu these Cominands, See the on-une help Under debue.
There a r e two main methad debuggtng MATLAB Proarams.
() One is to u s e the individual debugginá Comnands
bult 3nto MATLAB.
ci The other fs to use. the raphical debugger built Into
the MATLAB editor.
1 Break Roints:
dbstop Set twee Ways)
dbclear remoVe
dbstats - displayy
2 ExeCution
uSual C o m m a n d - start
dbeont -
hJindoN.
Open the frle that YOu Would ike to debug.
is loaded înto the editor
When the file is opened,lt
) is autematically color coced
The Syntax
(V Comments in the l e appear in dreen.
în black.
VD Variables and numbers In the ile aprear
(v1t)character strings în the file appear n red.
(Vn) Language. Keywoids tn he file 2ppear în. blue.
sraphies|
The MATLAB raphrs system s based on aa
hierarchical system Of coYe
graphics objects
These raphical classes are
suhclasses of handle
Handle Yefers to the obfecbE
- Handle raphics" is a set o on-level
t o maniPulate raphics objects. Waphics functians
These fraphic(Handle raphies)
control the charadteñshcs
fraphical chjects fenerated by MATLAB.
-MATLABs fraphics -facility is easy to use and
expandable..
Using faphRs in MATLAB 1eauires the understand in
Handle graphfes.
-Basc 2-D plots, Fancy 3-D Sraphics +otth ighting
and Cobrmaps are oW part MATLAB.
-slhg "Hand le Graphice" tools, Sophisticzted
(Hjhyavancrd)
Ldeelcred
raphics can be des igned
Basic 2-D plots:
visualization.
tools for
MATLAB Tncluses d a
commamfor pvaducing
The nmost basic and useful S h o n belo»:
command TEs Syntax s
2- plot 1s plot
plot(X.Y)
Mot(Values, yvalues,'style-option) (on
the
H e r e , V a l u e s 2nd yÝalues are Vectors conain ng
and Y-co.oxdinates of points on the gr2ph.
specihes
is optional arfument. t
Auo style -option
an
the folMowing:
() color.
b style (e.9 Solid, dashed, dotted)
Line
Versus X.
Sol Code pom-
X O: O1 1o
x takes Values tom 1to 1o Jtth íncremenb o
Y- 3 + +
y generates an r2y }Values fortach yalue z
plot (X)
Plots Y V2lues Versus their X caunter parts
12Create a plot"for y= 2 that the x-2xts has ioo lineary
Spaced data Poînts . GUTPUTTJ
Plot of x Verss y:
>> 1mspace O,Loo, 100):
x = Lo000
Y= X"2
plot(X,Y);
xlabel ('x):
ylabe(Y= x°122)
title('plot ofx Versus Y= x"24) O 20
IOO
>>y = x.'2;
aYea (x, Y)
xlael Cx
> ylabel(y=x*§2?')
title("Area of the cunve ye)
O O 20 100
X
a) labels;
annotating the Z-axis y-axis.
-Used for namlng o r
to the plot.
tSD Used forgiyin title shown bela;
belAs;
S han
ave
funchons
mamingfun
The abelinglon
fo h e
NamesONgies tite
ttle ( Pressure Varnatian') V2nahon,
Plot as, Pre ssUYE
functions 2re
xlabel, ylabel n d t t t e
benoted that, the,
I s to
Strngs.(string axfiuments)
Strins arefiment
D Axis;
Semicto of ae
The axCS
MATAB, a USer can control only Partof
Limibs.
The dher Jimits ae by MATLAB3.
Set auttmahcolly
1s acheved by
T h e partíal contol of axes Jimi bs
tth inf
Specitiing the axfs coRmand alng
Example: -Ris
Sets the imts at-5 and 10 The
axfs (5 10 -inf Inf])
y-axis Jimtts ave Set automatcally
9rid(taget--)
the major grid lines.
Irid provides the visibility
: DisPlays the major gridines for
the cuwent
nd on
axes
Example
P R C A R A M
isplay the. grid Jines for a sîne plot.
X linpacelo, lo):
Y sin(x):
PlotxY)
grid On
plot(xP)
title (Plot of y= ."2
-
1o.*x +15)
xlabel ('x');
ylabel (y':
grid on
(d style options arfiment in pot
command.
ls an optional
-The stye-option
three
Items They are
specifies
(1) Color o-the u n e
i) style of the J n e and
Aine
C1) Point-markerstyle O-the
character String Consístiany of
The Style-ophin 1s
a
characterS.
CmetWO or three líne
made u p h e colbr opbOn, t h e
The style-tption is
or a combinahon othem
OPtion, the marker option,
he are Shon b e l I ;
K back diamon
Exampe
Kih red Soltd n e
plot(x,) plots y Vercug a
Example: funchon
SuppoSe t h a t We Wanted to plot the
on the Same flot
l)=Sín 22 and its dexivative
Sin2z
Sol: Gien finchion ís, fx)=
Deoivsh ve
the funchn, dt
Cfx)) (sfn 2x)
=
X= O:P/1O0:2pY:
y1=sin(2x):
Y2 2 cos(2"x):
NoE All he Plots that here discuss So far are ine Plots.
These Plots, the data points are connecked by Jnes.
Gf) subplots
X-
comman S
Used t o make a few plob and
d
-The subplo
Place the plots side -
by side
The Syntax fs as shmon:
Subplbt (m,n,P
arfuments:
commanH Yenuves three ntefer
The subplot
m, n n d p.
I r s td be noed that a
Subplot Command creates
xes in tiled Posihons.
Sub
hWindois,
3
Caphxs
Man i n d
OSpecialized 2-D plotS:
-Specilized 2-D Plots are the Plots ith sprial aphics
-These Plots can present data în a more Effecnve
mannEY.
-USing the speciaized 2-D Þlots, a wide Varie Plots
Can be created.
s em i l ogx
t = l inspace ( 0 , 2*pi , 200) ;
x exp ( - t ) ; y = t ;
=
semilogx ( x , y) , gri d
gr id
' 2
x = e , y = 100 + e \ 0 ::; t ::; 27r
loglog t l inspace ( 0 , 2*pi , 2 0 0 ) ;
x = exp (t ) ;
y 1 0 0 + exp ( 2 *t ) ;
loglog ( x , y) , gr id
6 . 1 Basic 2-D Plots 185
2
r = 2 sin 5t, 0 ::::; t ::::; 271"
polar t = l inspace ( 0 , 2*pi , 2 0 0 ) ;
r = sqrt ( abs ( 2 * s in ( 5 *t ) ) ) ;
polar ( t , r )
270
2
r 2 sin 5t, 0 ::::; t ::::; 271"
x r cos t , y = r sin t
t l i n s p ace ( 0 , 2 * p i , 2 0 0 ) ;
f ill
r = sqrt ( abs ( 2 * s in ( 5 *t ) ) ) ;
x = r . *cos (t) ;
y r . * s in ( t ) ;
fill (x , y , ' k ' ) ,
axi s ( ' s quare ' )
2
r 2 sin 5t, 0 ::::; t ::::; 271"
y r sin t
x3
fapprox x - 3! , o ::; x ::; 2
error fapprox - sin x
error bar
X - Q ; .1:2;
aprx2 = x - x . '3/6 ;
er aprx2 - s in (x ) ;
�
errorbar (x , aprx2 , er )
186 Graphics
Yl e - x sin x , 0 :S t :S 1 0
Y2 ex
X = 1 : . 1 : 10 ;
y1 exp ( - x ) . * s i n ( x ) ;
plotyy y2 = exp (x) ;
Ax = plotyy ( x , y 1 , x , y2 ) ;
hy l = get (Ax ( l ) , ' yl abel ' ) ;
hy2 = get (Ax ( 2 ) , ' ylabel ' ) ;
s e t (hy1 , ' string ' , ' e - - x s i n ( x ) ' ) ;
se t (hy2 , ' string ' , ' e - x ' ) ;
sin(x)
y = --- , -37r :S X :S 37r
X
x = l inspace ( - 3 *p i , 3*p i , 1 00 ) ;
y = - s i n ( x ) . /x ;
area ar e a ( x , y)
xlabe l ( ' x ' ) , ylabel ( ' s i n ( x ) . /x ' )
hold on
x1 = x (46 : 5 5 ) ; y 1 = y ( 46 : 5 5 ) ;
are a ( x l , yl , ' f a c e c o l or ' , ' y ' )
Histogram of 50 randomly
distributed numbers between
0 and 1.
hist
y � randn ( 50 , 1 ) ;
hist ( y )
04
f = e -t/S s i n t , 0 ::; t ::; 2 1r
90
1.5 2.5
1
z - x 2 + xy + y 2
2
f x f :S 5 , f y f :S 5 .
contour r = -5 : . 2 : 5 ;
[X , Y] = meshgri d (r , r ) ;
Z = - . 5 *X . -2 + X . *Y + Y . - 2 ;
cs = c ont our (X , Y , Z ) ;
c l abe l ( c s )
z x 2 + y 2 - 5 sin(xy) �
l
-
'
-- ' ' ' ' ' ' ' --- - - � -
' ' ' ' ' " ' ' ' ' � - ,
f x l :S 2 , f y f :S 2 .
_ , , , , , , , , , _ _ _ �
, , , , , , , , , , _
\ \ \ \
\\\ \ \ \ , , ,
\ \ \ \ \ ' ' " ' ' I' 1I \\ \\ \
quiver r = -2 : . 2 : 2 ; I I \ I I \
\ \
z x 2 + y 2 - 5 sin (xy)
f x f :S 2 , f y f :S 2 .
pcolor r = -2 : . 2 : 2 ;
[X , Y] = me:>hgri d ( r , r ) ;
Z = x . - 2 - 5 * s in ( X . *Y) + Y. -2;
pcolor ( Z ) , ax i s ( ' off ' )
shading int erp
PaÁes 1e4-1P2 ro ch
r ce MATA
1 -2>2 fnPdf
specialized graphie
fasy-t-uSe
some
there are
OtCTnMATLAB, tunchianS.
tuncioms. They are ez plotter
ezeontour
gives a
oi ndow gives
în 1he c o m m a n d
raph2d
NE Typing help 2 - D raphie
for feneral
Of fiunchion s avallable
3-D plots:
X X
X
3-D plots means, Three-dimensional plotS
Three -dimensional plots are used to pre sent d
that has more than t y Variabes.
MATLAB PrOvicdes various options for displayns
threedimensional data.
They are: ciy Línc
plots a) Wire Plats
(f) Suface plots and (1V) Mesh plots.
T h e 3-D plots can be fotmatted to have a
Special appearance and Special eppearnce) tfects.
funchons
B y typing help sraphd in the cammand indon
ist-of--funchions available tor 3-D raphics are
displayed.
Some ofhe commonly used hunchons are. isted bela:
Plot3 function
The function Flot3 (s the 3-D Verim plot.
- USe Puncions
Easy-tD
3-D plots e
-Some tasy-to-use funChions related
to
(U ezsurf
(i)ezmesh
Citi) ezplet 3.
These funchions r e ez-Stable
dmain he fimcticn.
rid.
To create
thc pl»t
tep-2
as
Command
he enerafn q mesh or surf
shown below
points
ample: 2
2 and
domain
functhionz
9 OVer the
for the
X=-1:O:L:3
Y = O1 4
meshgrid (XY): meshgrs i s a i l t-in
X,Y]= funthmtd ereate X rnd
Ymetnce
z .*Y. "2-/(x. "2 +Y. 2)
rmesh (X,Y,z) Tue surfi z) tor
Surtace plot|
xlabel(x'):
Y1abel (Y)
zlabel (z');
-
S to e noted that
the mesh and uYE
Commands can abo be used with the form
cchl2 and SuY (2
-
matYix.
NOIe
Command ecutes, the gricsp
when the mesh
y default.
Command, a bOK Can be dran
0sing The bCx On_
around the Plot.
ontouPo representatonS
ae t h o - - d i m e n sional
-Contour Pl bts
three - d i e n s i o m a ls u t a c e s
real
a unchonfaN) of tso
- IEs used td visualize
variables.
he reqLure arectangular
Before a Cantour 1s created,
-
Using MATLABS Ctar -tuncti on, The
contou Y the
dats 2 t plotktd.
can be
- o EX 2mple, the funchan flx, y) x23fy*
hitten 2s a COntDur funchon .2,
There=xs
#3*x + Y."2
Contou C
xemple points
on 5)
6L £quDlly sPaced
Ceate a vector x of n Lt tI
fru2lly sfased poins
21
and 2 vector Y pointisand
tw C e a t e r a y s of rid
Semeshgrid
Xx'a-Bx +Y"2 2 fach
the fnchicn
fCX,Y)=
tValuate
25 Contóurs G
c o n t o u r plot t h
create a
r i d PGiNt, and
for the 2xis labes
vectors x and y
using the
add 2 grid and title
Proam
1inspae (-3,3, 6
:
Y i r n s p a c e( - 4 , 4 , 3 1 D ;
x , Y=meshgrid(y,),A;
=
x.33x + Y2
Contour(XY, F 2 )
grid on
xlabel ('x);
ylabel ('Y'):
x'3 -3x+ Y2'):
title('f(XY)=
c o r t o u r lakels:
contor label
the
MATLAB tunch on, clabel
vsin
Can b e added3.
mple
=
ContoUur(x,Y,F, 1S)
Ch]
c l a b e l ( h )
Example: EXampt
-contours a funchon. contours a t thwerty levels
Contour CXY Z, 20
Y Iinspace (o,41Pi):
Y meshgrid(X );
2 Sin (x)+Cos (Y);
contour(X,Y z)
For plotting
ContoLer 3 (X,Y,Z,n)
a-Contour levels
= nurm b r
the funchion fornt is
a 2-p contour plot,
-For plotting
Contour(XY 2,n)
M2 htm ber qContor Ieels
Stem Plots:
- A Stem plot iS a tho- dimensional Plot.
a base-ine
-
Syntex forms?
stem (x)
stem(XY, FFI|)
Stern (x,Y, 'Efl1,--.-)
- Using Stem Command, a discrete simal Xn) Can
be
repre sented fraphicall
NOte: stgnaD-> The dlscrete time
signal(draital
Cre at specffic
fnstants
Examples
Plot single Data series. 2/T
data Values bemeen
Create a stem plot of 5
and 2(T
Sa Progr2m
fiqure
2tpi, 5
Y= linspace(-2tpi,
stem (Y()
enes
-plot meltiple pat2
a t a Series s n d a tso - Csumn roatmx
P l o t tro
PrOgram
Figurc
lmspace(,
2* P, 5O);
Y=
Y= C o s ( x ) , o . 5 * s i n ( x ) ] :
Stem (Y)
3 - dimehsional
stem
Command Teneraes a
Stems
plot. bela:
fs s h o n
The funchon format ol stem3 command
stem3XY2)
markers and
pbints h
hisCmanddrais sequenti2
from the Y Plane.
( Vertical l i n e s
Exampe
7PYos m
t= O: O2 :10
X=t
y: sinlt
zt1:5
Stem3XYZ,f1Il")
grid onn
xlabel C'x')
Ylakel ('y')
zlabel (z')
ezplot command
Use
ts plotter funchon shkh is £asy-to--
a
The y t a x fs
omín, xmaxJ
ezplot( functon',
okay
sinfle variable, (H
sCemmand takes the fundhion
a
command They
here re few Variants (coLSins) for ezpld
3re (V)ezLontaurf(V) EzSurf
ezpolar db ezplstz (r) ezcotou
and V czsufC.
replot a
Tts
t the conmand. wed td plot 3-D Parametric curves.
pefault donain O<t2tt. This camm=nd tkes xit), YO i
zt) as input arauments.
ExznAe
plot t ) =
E.cd(3TE), y(E) =t.sin StTt) Md Zt)=t for xtx27.
et=t*Co (3*prTt)
y tsml3*plt)
z
1D ezcontaur
Hots a contour plot
v ezcontour
- I t is a verientof ezcontour.
Ex 2nple
plot the filled certours ef ze co coYexpV(AY/4
aveY the domain
(V) ezsYf
This command odces sunning suace plots in 3-D.
2= E(y) fs taken as fnput arfument of ezsur
Exmple:
Plot the sutace plot for z= -5/(14 Z +y) over the Amain
z 1 2 and yl<3.
2 nline (s./L4X2+Y.2));
ezsurf(-l-3,3,-3])
v ezsutc
plot AJith it's
Ths command Combines h e Surface
contouY plot,