0% found this document useful (0 votes)
82 views

MATLAB Unit 2 Study Material

This document discusses scripts and functions in MATLAB. Script files are M-files that contain MATLAB commands and can be used to repeat commands. Function files contain function definitions and are used to reuse code. The document provides examples of a script file that solves a system of linear equations and discusses how to debug MATLAB programs using built-in debugging commands and the graphical debugger in the editor.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

MATLAB Unit 2 Study Material

This document discusses scripts and functions in MATLAB. Script files are M-files that contain MATLAB commands and can be used to repeat commands. Function files contain function definitions and are used to reuse code. The document provides examples of a script file that solves a system of linear equations and discusses how to debug MATLAB programs using built-in debugging commands and the graphical debugger in the editor.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

UNIT-II

Seripts and Functions:

soipts have the ability to overrite the Jo Kspace


Variables.
Funchons ate prorams that accept inruk arfuments'
and return 'cutput aYguments
MATLAB has hundreds o built-in functions.
Tf e nced to execute repeated euences qommnds.
We create 2 seperate file h17h Such cOmmanda

This file s called the Script file


M-FILE-
h e Proframs Hve. htite (Oser títes) in. MATLAB are
Called M-f1les
The tM-files are. ordhary ASCIT text files oith 3n
xtensíon .m
M - f e s can be creafed usind an édltor or
oYd Proce ssing application.
M-Files are tNO tures
(1-)Scriptfiles and
2 Function fles.

Script Files:
7

-A seript file iS a user-created-fAle with a set o Valid


MATLAB COmmandstn ít.
-Script files re usuay ealled as M-f°les.
They have 2 filename with xtensionm .m
A Seript file is cYestes
from the file menu OMATLAB
desktoP s folloS
Pfle- Neh Blank M-file
A Script file fs x e u t e d : by tupind ibs name
at the Command prompt.(on the comm and ine).
n
geral, soript files woIk a n álobal VaY1ODIC S .
(61obal vaiables -Variables curvently precent im the
WorkSPace),
- AFTEY a scrípt file fs exected, the esults e
eft
n the orkspre,
A A ScYiptile may contein any number q cmmands
- T h e s e f i l e s a r e Useful ohen. Ne h a v e t o e p e a E a

Set q C m a n d s seeral timeS.

-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.

S Fam he above set l i n e ar éuahins corsider


that 5 2Y
A 2r-1
Br

Aderpends on the Paranmeter Y

I n £ach case, he Shall{nd fhe determinant+


matrlX A .
W e Nsite a et MATLAB COmmand tD dob
the job.
W e Store these commands fn a seript-frle
and Save the l e using: So vEx m CFlle n2me)
On, solvex m wi|be Saved on Some disk drive fn
Same divectovy (r folder),
progt>m m- --
This is the seript file solvexm'
asD Cakulates
T t Solves "he Anear£quations and
detCA)D.
A T5 2tr 3 62r1 2 r - 3tr1:%ereate
maix A.
b 2:3:5]: Creatte
Vectorb
det-A detCA)# 7Pind he
determinant
X = A\b
Find x

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 =

This s the output.


6A
- O. O 3 1 2

O: 2344
1.6815

Who checkthe Variables in he


WOKspce.

t d be noted that ris asSihed to2value 4,outside


he sript fi|e.
PLtt sill solvex PiCkS uP Ths Value snd computes A.
funchiom Ftles
-A fuetfon fle is also an M-file havin a funchion
definition Jine on the top.
The sytax q h e -funchion definition line is as follo

function Loutput vavisbles] =funcior_name(imput vari

tere the function-name must be the Same as the file name


in shich the. furmchion (s N7Ttten.

Examples
Function befniton Line Fle Name,
fun ction [rho, HF] motion (XY,t) = motioN)

functhion theta THETA (X, Y, z) THETA m

fuunctiom circler) circle m

-Ote;
The first sod in the funchior definitian line, functian
must be typed in loercase.

funchoym ioput List


Anatomy of afunction ftle atrt 1Ame
St
defnitfn e

function xout, yout)= functiame(Xin, yin)


HA
Hne addL line deScription of
function here
C o m m e n f
Wite ón-Uine help comments here
ine
usea by . nclude UouY name and date
o n - i r e help

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.

hen WeLxecute this funcion in


MATLAR.cts shown
>clear al
>>[detA, Y] = Solvexf(1): take rei and exarute solexf: m
det A % display the Value det A
det A =
64
Y

- O0312
O2344
1 6815

>Who

Your Variables are


detA Y
h e n Executed, only the Variables in the Outplt Jist Will be.
eft i The sokspace
methods tn MATLABB:
Debuging
niCh YOu Sate and fix errars

-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.

-Under debuging commands, the folooin a r e coyered :

1 Break Roints:
dbstop Set twee Ways)
dbclear remoVe

dbstats - displayy

2 ExeCution
uSual C o m m a n d - start

dbeont -

continue ntil breakpoint or end


dbstep execute cuient line in function then stop a5ain

dbuut- quit debug mode and Stop executhión.


3 Combext
dbstack- dieplay "cat lfst"
dbup 3o Up
do uP aa function ( 0 Uu Can display Van>blet
functieT\in its wTAKSPaCe
dbdoan- go back dovin
Under faphical debugger , the Cmm>nd iS
edtt
Odng the. symbolic debuGEr ith MATLAB
is supplied
h e Symbolic debuger
TThe
ith the MATLAB tor.
This debugger is inteqrates

To uSe the debuger,

C1 Select File/Open menu selection ín the MATLAB COmmand

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

t) point-marker etyle (s9, o, +, *).


must have the samne
The two Vecitors Values a n YVlucs,
1enfh
-

For twO CAumn Vectors and y £ach lengh n,

plot (x, V) plots y Versus Aith a Soid ine (tefault line


yle)
plot(xY,-) Plots y Verses ith a dashed une
plotC) plots the elemerts of asainst heir row
index.
- JhenPlot fiunction s kectted, MATLAB OPens a fsuut Hindor) Yl
2

splap the Plot în that oinbo.


Creahng a simple inear plot
LGhven a inearfomu la; Y= 32+t.create an m-frle for plot y

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

el ereate a plot y= that the x-axis has Do Jinearly spaed


data
points. Ao shade 1he are a under the. Curve,
Area dtheaurve. yz
>> X = linspacelo, L0o, 1Oo): 0000T

>>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

labels the 1-2xis.


xlabel
labels the. Y-axiS.
ylabel
title's the lobt.
ttle
- a x i s with PiPe
Labels the
eg: xbbel('re Length')
length
wíth Flud
pressue)- Labels the y-axis
ylabel (Fluid PessuNC .

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)

Xlabel Syntax; y1bel symrtax


(1 x1abel(txt) 0 ylabet (txt)
xlabeltarjet,bxt) 2 ylabelltarget, tst)
(3)
(3 x1bel(-- Name, Value ylel (-,Name, Value)
(3
t xlabel--) (EYbet -)
gttegtie Sitax
(1 title(titetext)
(2) titletitetext, sustitletevt)
t i t l e (--,Nzme Value)
4 title (target
In addiion tO the above three arjuments íe, xlabel,
Ylebel, itle thee. is one more Command viz text
text Command Suntax fs shonbela!

text(-co.ordinate, y-co ordnate, 'terE')


Here the. Co-ordinate values 2ye Eaken from. the current
Hot
Etext(26, 'note this dip') hites 'Note this dip'at
the locatin (2.o, 6) fn
he plot coodinates .

a n a n t of textcommand is the g r X E Tt only takes a

Strins arefiment
D Axis;

-Jrth axis command, Yoll, Can change the limits of


a plot that is generated
tax axis(min Zm Ymin Ymx

-Using the abdVe Com)and, fhe CuLrent axes Amit for


-axis ave changed to Lmin and imaE
Ano, he cument axes imits for V-axis are Changed ty
ymin and Yma vespeCtively,

The xis Command fs specitied fter the Plot_Comand


tn a MATLAB pPraram
The axis Command may abo be uSed to zoom ?n or
to Z0om cut on a particilar section e the plot.
arfumestS for the axis
Some usefil, predetined staing
Command are
both axes,
sets eqUUal scale n
axis Cequual)
sets the default rectanrilbr
axis(suLare') rame to a squPre
axisnovmal) resets the x i s to default
Values.
c Y e n t axes limits,
axs(axis) Preeres h e

8xts Cofe) remoe S the Soundingrame


And the tick marks.
-he. above commarnds are USed for Ax+s eertte

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

22]) loLier Jtmit of the -axis


oxfs(C-5 inf -inf Sets the
the
n the Upper Jimit of y-axiS.
s e t 2utomahcally.
other thwÐ m i t s are
Crid
-This Comman il1 Aisplay or hide axes oid ines.
Syntax
i d on
i d of
9id
grtd minor

9rid(taget--)
the major grid lines.
Irid provides the visibility
: DisPlays the major gridines for
the cuwent
nd on
axes

rdott Remoes all id Aires from the curent axes or


chart.

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

Gyid inee can be added or removed from the Plot.

-xamplei -10+ 15 ith itles


Generate a plot cf the function y=
1abels and grídlines
Prxfram X OL: 10
Y= 2 ' 2 - 10. r + 15

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 ;

color stle-option ine style-option| Marker yle -option

Y yellow solid Plus sign


dashed cvcle
magenta asterisk
dotted
cYY X-maK
dash-dot
red
mo lîne Point
reen
up triangle
blue
white S siare

K back diamon

Exampe
Kih red Soltd n e
plot(x,) plots y Vercug a

plot(xY,:) Plots y versus Hith dotted ine.

plot(,9, 'b--") plots y versus r with a blue dashed line=


y versus (th)
Plots as unconnected pon
plbt(7,y,+ ')
maked by a t
eMultipe plots
-K
n MATLAB, i t ts poeeble t plot mu/hiple fnctONS
n 1he Same y a p h

B y including o e than one set of (zy) Values in


the. Hottunchon, a vser can plot multipe. PlotS

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)
=

=2. coh 22z


have tho functions, 1) sin2X 2nd 2)2CA2,
-NOns, we
to be plotted an The S a m e sraph.
oXValues and the Coresjondng y'values
-A set £achfunchon.
are generated tor
are Ísted in the Plot
Both sets q a y9 Values
funchcOn
% program

X= O:P/1O0:2pY:
y1=sin(2x):

Y2 2 cos(2"x):

plot (X, y1, x, Y2);

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.

indw divides the gYaphics


indo into mxn
-A subplot
SubhindonS
the plot fenerated by the next Plotting cOmman d
TE puts
into the pth ofnow.
command:
For fxample, the
SLuhplat (2,2,2)
plot(xY
Sub indws
vides the raphics sindy întp 2x2, T.ey four
NlI Le n the third stb noindw .
The plot y versus x

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.

These plots înelude:


) Bar plot (it) staîrs plot (it) tem plot iv) pe Pot and
more
The Special gvaphes
plots are framed usins some plotting
functions.
Funhon Descrition
area Creates a flled aYea Plot
bar Creates a bar r a p h

arh Creates a heizontal bar draph


Come nakeS an anímated 2-D plot

CompaSS ereates arro graph for complex


Mum bers.

errOrbar Plots a rah and pits error bars.

tathek makes a feather Plot.

fil rawsled polygons of specified


Color.
makes histograms
hist
Creates plot ith lofscale n both
loglog the -axs and the. Y-axis

pre CYeates pie.chart


ose makes gled híto grams.
Semilogx makes semilog Hot Wih log cale on
the -3xis.
stairs Plots a stair fraph
Stem plots a stem
draph

Polar Plots curves in Polar coOdinates


184 Graphics

Function Example Script Output

f (t) = t sin t, 0 ::; t ::; l01r

fplot ( ' x . * s in ( x ) ' , [0 l O*pi] )


fplot
Note that the function to be
plotted must be written as
a function of x .

s em i l ogx
t = l inspace ( 0 , 2*pi , 200) ;
x exp ( - t ) ; y = t ;
=

semilogx ( x , y) , gri d

x = t, y e' , 0 ::; t ::;


oo'
= 21r
semilogy t = l inspace ( 0 , 2*pi , 20 0 ) ;
semilogy (t , exp ( t ) ) ,.

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

Function Example Script O utput


90 1 . 5

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

bar t l inspace (0 , 2*pi , 200) ;


r = sqrt ( abs ( 2 * s in ( 5 *t ) ) ) ;
y r . * s in (t) ;
bar ( t , y )
ax i s ( [O pi 0 inf ] ) ;

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

Function Example Script Output

World p opulation b y continent s .

c ont = char ( ' As i a ' , ' Europe ' , ' Af r i c a ' , . .


'N. Ame r i c a ' , ' S . Amer i ca ' ) ;
pop = [3332 ; 696 ; 694 ; 437 ; 307] ;
barh (pop)
barh f or i = 1 : 5 ,
gt ext ( c ont ( i , : ) ) ;
end
x l ab e l ( ' P opulat ion in m i l l i ons ' )
Title ( ' World Populat ion ( 1 99 2 ) ' ,
' f ont s i z e ' , 1 8 )

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 ' )

World population by continents.

c ant = char ( ' As i a ' , ' Europe ' , ' Af r i c a ' , . .


' N . Amer i c a ' , ' S . Ameri c a ' ) ;
pop = [3332 ; 696 ; 694 ; 437 ; 307] ;
pie p i e (pop)
for i=1 : 5 ,
gtext ( c ont ( i , : ) ) ;
end
Title ( ' World Populat ion ( 1 992) ' , . . .
' f ont s i z e ' , 1 8 )
6.1 Basic 2-D P lots 187

I Funct ion Example Script O utput

Histogram of 50 randomly
distributed numbers between
0 and 1.
hist
y � randn ( 50 , 1 ) ;
hist ( y )

-1.5 -0.5 0.5 1 .5

04
f = e -t/S s i n t , 0 ::; t ::; 2 1r

s t em t �l inspace ( 0 , 2*pi , 200) ;


f = exp ( - . 2 * t ) . * s in ( t ) ;
s t em (t , f )

r2 2 sin 5t, 0 ::; t ::; 21r


y r sin t

stairs t l inspace ( 0 , 2*pi , 200) ;


r �s qrt ( abs ( 2 * s in ( 5 *t ) ) ) ;
y r . * s in (t ) ;
stairs ( t , y)
axi s ( [O pi 0 inf ] ) ;

90
1.5 2.5

z = cos B + i sin e , - 1r ::; () ::; 1r


th -pi : p i / 5 : p i ;
zx c o s (th) ;
compas s zy s in (th) ;
z • zx + i+zy ;
c ompas s ( z )
188 Graphics

Example Script Output

y = t sin t, 0 ::; t ::; l 01r

q = l inspace ( 0 , 1 0 *pi , 2000) ;


c omet
y = q . * s in (q) ;
c omet ( q , y )

(It is better to see it on screen. )

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 \
\ \

\ \ \ \ I ' ' \ \ \ \\\\


[X , Y] = meshgri d ( r , r ) ; ' ' \ \. \ '\ \ \ \ \ \
- - � ... , , , , , , , , ,
z = x . - 2 - 5 * s in (X . *Y) + v . - 2 ; ' - - - .... .... , , , , , , , .... ....
,
- - - - .... ..... , , , , , , ... - �

[dx , dy] = gradi ent ( Z , . 2 , . 2 ) ;


\
- - - - ..... ...... ..... , , , , • • 1

.._ _ __ _ , , " ' ' ' ' ' ' '


. - - - ...... ....... ...... ...... ' ' ' ' \

\ ' - ..... ' ' '


quiver ( X , Y , dx , dy , 2 ) ;

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

Qsme f them are: ezplot, ezpelar ,

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.

MATLAB ako PYOVides Some built-in-funChonS tor


visualizîng 2-D data.

Thefaci lities provided by MATLAB înclude buflt tn

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:

Fmchiom Degori ption


plot3 Plots curves în space
Stem3 Ceates discrete data ploE Th Stems in 3-D

bar3 plots 3-D bar raph

barzh Plots 3-D honzontal bar graph

Makes 3 -D Pie chart


ples
Comet3 Makes animatel 3-D June Plot
frlls draNSflled 3-D polygons
eontour3 M2kes 3-D Contour plots
Deseription
FunctiOn
3-D
helds 1n
yuiverz3 d r a n s Vector
in 3-DP
catteY3 makes catter Pots
surfaces (wire -frame)
3-D mesh
mesh draws ITh Contors
alcmg
3-D mesh surtaces
meshc drows
mech Surfces
hith refeene Pag
3-D
meshz dravss

Surf Cieates 3-D Surface plots


with Conturs.|
3-D Surtce Plots almd
Surfc Creates

3-D Surf2te Pots ith specified


Surfl eeates
ight Source.
trimesh mesh plot oith triangles.

trisurf Surface tlot iith Triangles


Sice draws a volunetric suface With Slices
Katerfall plot of 3-D data
Waterfal Creates a

eylinder enerates a cylinde

ellipsoid Jenerates an ellipsoid

sphere Jenerates asphYE

Plot3 function
The function Flot3 (s the 3-D Verim plot.

The general syntax s


P l t 3 ( 9 ,z, 'style-opion) r Plotz4,2)
-

This conmand il plot a cuve tn 3-D Space2


The C r v e will have a speciic l i n e style

- For Ex 2m ple, the comman

plot3(r and(1,10), Y2nd (A,10), Y>nd(1, 1o)

qenerates lo Yandm oints in 3-D SPace, and joins them


Sith ine.
Annotations in3-D Plots
e dene by
Amotations Namíng) n 3-D Plots c a n
under 2-D Plots.
using the funchons alveady mentioned
- That 1s,
xlabel, ylahel, t'tle, text 9rid Ete
addia to these, a new funchn zlabel ls addes
in z-D plots.
-Using Gid command for 3-D Plots, the 3-D Curves
n SPace hill aPPear better.

- 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

Mesh and Suface plots


three-dimencicnal plots.
-Mesh and Surtace plets are

plotting functicns CThe -folm


are s cd ftor
They
ZfC,Y)
are mdeendernt Variables.
Here and Y
is a depen dent Varia ble.

The Vlue Oz Carn be calculated for any commbination


ard and meshz
meshC
Osing the fiunchions Such a s mesh
Mesh plots c n be plotted.
the functhcns Cuch as, Su SutC, Surfl and
Using
trisurf Surface plots C>n be plot ted.
Cieated în three Steps. They e
Mech and s:fce plots a
hrid in the iY Plne
t h a t cOvers th
te ; To create a

dmain he fimcticn.

Value ) z af each foint he


Step-2 To calulate The

rid.
To create
thc pl»t
tep-2
as
Command
he enerafn q mesh or surf
shown below

mesh (X, Y, z) 2nd SurfCoY, )


o.otdinates
are matrices with t h e
here X nd Y
t h e . rid.
matrix STh The Value zat 1he grTd
z is a

points
ample: 2
2 and
domain
functhionz
9 OVer the
for the

194 plot mnesh (pr Surface) plot


mesh Plot or SuracePioE
PrOrm for Plotting a

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
-

Ustng mesh2) and SurFCZ),the Vlues q 2 2


Plotted a s a funchion q h e i r addresses in h e

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,

array funchon Values (Yt)at a


rid o
Points X, j ,2.---n 2nd Y71= 1,2..-m.

Points e three sbe are Tollane


TO Cre ate grid
as shoon belo;
varible.
Create a vector Xof n grid points for t e x
step) the Yvarizble.
Vector Yo
n gris Points for
Cree
sk
Use the meshgrid flnchn Y medgid(x,Y) ED
stit Create aría X, y.

-
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

pro gram YProgy-m


sa
X= 1fnspacel-2°Pi, 2pi): LXz]= PeakS;

Contour CXY Z, 20
Y Iinspace (o,41Pi):
Y meshgrid(X );
2 Sin (x)+Cos (Y);
contour(X,Y z)

3-D Contour PlOt, the fundion format is,


a
-

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
-

Tt displays data as ines extendind from


along the X-axis
Us ed to denerate stem
n MATLAB, stem COmmarnd fs
Plot
The sytax 1S: stem(X,Y)

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

hasa r e defined s t only


Of time.

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)

SPe c Stem md hMarker oPtons.


dotted i n e
aCreate a sem plot and Set the Aine style to
Hhe mrker symbos to diamonds, and h e color to r e
ustng he Linespec oPHn.
Progrorn
iguree
x= linspace (0,
2t pi, 50)
Y exP),*sinc)):
Stem(XY, ':diamónd ' ) ;
Exmple:

Yr= C988 :1941:


Sle =[R 12 20 22. 12 24 24]
Stem ( sle)

stem3 Comm 2nd

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

imits O he axes 2s inPut (Here Xmin


S|l abo Consider the Xmax)
21T<? <21T
befawt imits are: -

Exmpe, between o and 20.


e IOCsA) for
Piothe function, f ) =

ezplot(exp(-1 **). 'co(X),


LO, 20)
an ezPlot
he b o v e command
wilT PYOuCe

command They
here re few Variants (coLSins) for ezpld
3re (V)ezLontaurf(V) EzSurf
ezpolar db ezplstz (r) ezcotou

and V czsufC.

cerpolar versin ot ezplot


T E fS the o/2r
YCefs ken a s tnPUut ardfLment
Defult domain (limits) are O<O<2T,
fur O<e<2TT
nple? plot, rle)= l+2 sin(2e)

sol: Y inne C'+2*(sfn (2*t)."2')


ezpolarLr) .

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

-2= FX, ) is the înput arfment


Default domain: -2T <21Tnd -2.t<Y <2IT
Exemple
Plot the contous f z= cacoy exP(-VC+u)4) overThe
defaulE donain,
Sol = nline (cesCx).Eos(Y). 'exp(- s r t(x.2+ Y.2)/4),
ezcontourlz)

v ezcontour
- I t is a verientof ezcontour.

T prOduceS flled cotorS,

Ex 2nple
plot the filled certours ef ze co coYexpV(AY/4
aveY the domain

z = inlineCcolx)cosy) exp(- sqrt(Cx.2 + y.2) / 4 ) ) |


e acsntourf(z, -5,51)

(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,

Tis a Variant of ezSuYt


EXmple z=Inline (-5./(L+X,2+Y."2));|
ezsurtc(Z,-3,33))

You might also like