Chapter5
MATLABGraphics
In this chapter we describe more of MATLAB’s graphics commands and the
most common ways of manipulating and customizing them. You can get a
list of MATLAB graphics commands by typing help graphics (for general
graphics commands), help graph2d (for two-dimensional graphing), help
graph3d(forthree-dimensionalgraphing),orhelp specgraph(forspecial-
izedgraphingcommands).
WehavealreadydiscussedthecommandsplotandezplotinChapter2.
Wewillbeginthischapterbydiscussingmoreusesofthesecommands,aswell
astheothermostcommonlyusedplottingcommandsintwoandthreedimen-
sions.Thenwewilldiscusssometechniquesforcustomizingandmanipulating
graphics.
Two-DimensionalPlots
Oftenonewantstodrawacurveinthex-yplane,butwithynotgivenexplicitly
as a function of x. There are two main techniques for plotting such curves:
parametricplottingandcontourorimplicitplotting.Wediscusstheseinturn
inthenexttwosubsections.
ParametricPlots
Sometimesxandyarebothgivenasfunctionsofsomeparameter.Forexample,
thecircleofradius1centeredat(0,0)canbeexpressedinparametricformas
x=cos(2πt),y=sin(2πt)wheretrunsfrom0to1.Thoughyisnotexpressed
asafunctionofx,youcaneasilygraphthiscurvewith plot,asfollows:
T = 0:0.01:1;
6768 Chapter5: MATLABGraphics
plot(cos(2piT), sin(2piT))
axis square
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
Figure5-1
TheoutputisshowninFigure5.1.Ifyouhadusedanincrementofonly0.1in
theTvector,theresultwouldhavebeenapolygonwithclearlyvisiblecorners,
an indication that you should repeat the process with a smaller increment
untilyougetagraphthatlookssmooth.
Ifyouhaveversion2.1orhigheroftheSymbolicMathToolbox(cor-
respondingtoMATLABversion5.3orhigher),thenparametricplottingisalso
possiblewithezplot.ThusonecanobtainalmostthesamepictureasFigure
5-1withthecommand
ezplot(’cos(t)’, ’sin(t)’, 0 2pi); axis squareTwo-DimensionalPlots 69
ContourPlotsandImplicitPlots
Acontourplotofafunctionoftwovariablesisaplotofthelevelcurvesofthe
function, that is, sets of points in the x-y plane where the function assumes
2 2
aconstantvalue.Forexample,thelevelcurvesofx +y arecirclescentered
attheorigin,andthelevelsarethesquaresoftheradiiofthecircles.Contour
plotsareproducedinMATLABwithmeshgridandcontour.Thecommand
meshgridproducesagridofpointsinaspecifiedrectangularregion,witha
specified spacing. This grid is used by contour to produce a contour plot in
thespecifiedregion.
2 2
Wecanmakeacontourplotofx +y asfollows:
X Y = meshgrid(-3:0.1:3, -3:0.1:3);
contour(X, Y, X.ˆ2 + Y.ˆ2)
axis square
The plot is shown in Figure 5-2. We have used MATLAB’s vector notation to
3
2
1
0
-1
-2
-3
-3 -2 -1 0 1 2 3
Figure5-270 Chapter5: MATLABGraphics
produceagridwithspacing0 .1inbothdirections.Wehavealsoused axis
squaretoforcethesamescaleonbothaxes.
You can specify particular level sets by including an additional vector ar-
√ √
gument to contour. For example, to plot the circles of radii 1, 2, and 3,
type
contour(X, Y, X.ˆ2 + Y.ˆ2, 1 2 3)
The vector argument must contain at least two elements, so if you want
toplotasinglelevelset,youmustspecifythesameleveltwice.Thisisquite
useful for implicit plotting of a curve given by an equation in x and y.For
example,toplotthecircleofradius1abouttheorigin,type
contour(X, Y, X.ˆ2 + Y.ˆ2, 1 1)
2 2 2 2 2
Ortoplotthelemniscatex −y =(x +y ) ,rewritetheequationas
2 2 2 2 2
(x +y ) −x +y =0
andtype
X Y = meshgrid(-1.1:0.01:1.1, -1.1:0.01:1.1);
contour(X, Y, (X.ˆ2 + Y.ˆ2).ˆ2 - X.ˆ2 + Y.ˆ2, 0 0)
axis square
title(’The lemniscate xˆ2-yˆ2=(xˆ2+yˆ2)ˆ2’)
Thecommandtitlelabelstheplotwiththeindicatedstring.(Inthedefault
string interpreter, ˆ is used for inserting an exponent and is used for sub-
scripts.)TheresultisshowninFigure5-3.
IfyouhavetheSymbolicMathToolbox,contourplottingcanalsobe
donewiththecommand ezcontour,andimplicitplottingofacurve f(x,y)=0
can also be done with ezplot. One can obtain almost the same picture as
Figure5-2withthecommand
ezcontour(’xˆ2 + yˆ2’, -3, 3, -3, 3); axis square
andalmostthesamepictureasFigure5-3withthecommand
ezplot(’(xˆ2 + yˆ2)ˆ2 - xˆ2 + yˆ2’, ...
-1.1, 1.1, -1.1, 1.1); axis squareTwo-DimensionalPlots 71
2 2 2 2 2
The lemniscate x -y =(x +y )
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
Figure5-3
FieldPlots
TheMATLABroutinequiverisusedtoplotvectorfieldsorarraysofarrows.
The arrows can be located at equally spaced points in the plane (if x and y
coordinates are not given explicitly), or they can be placed at specified loca-
tions. Sometimes some fiddling is required to scale the arrows so that they
don’tcomeoutlookingtoobigortoosmall.Forthispurpose,quivertakesan
optionalscalefactorargument.Thefollowingcode,forexample,plotsavector
fieldwitha“saddlepoint,”correspondingtoacombinationofanattractive
forcepointingtowardthexaxisandarepulsiveforcepointingawayfromthe
yaxis:
x, y = meshgrid(-1.1:.2:1.1, -1.1:.2:1.1);
quiver(x, -y); axis equal; axis off
TheoutputisshowninFigure5-4.72 Chapter5: MATLABGraphics
Figure5-4
Three-DimensionalPlots
MATLABhasseveralroutinesforproducingthree-dimensionalplots.
CurvesinThree-DimensionalSpace
Forplottingcurvesin3-space,thebasiccommandisplot3,anditworkslike
plot, except that it takes three vectors instead of two, one for the x coordi-
nates, one for the y coordinates, and one for thez coordinates. For example,
wecanplotahelix(seeFigure5-5)with
T = -2:0.01:2;
plot3(cos(2piT), sin(2piT), T)
Again, if you have the Symbolic Math Toolbox, there is a shortcut
usingezplot3;youcaninsteadplotthehelixwith
ezplot3(’cos(2pit)’, ’sin(2pit)’, ’t’, -2, 2)Three-DimensionalPlots 73
2
1.5
1
0.5
0
-0.5
-1
-1.5
-2
1
0.5 1
0.5
0
0
-0.5
-0.5
-1
-1
Figure5-5
SurfacesinThree-DimensionalSpace
There are two basic commands for plotting surfaces in 3-space: mesh and
surf.Theformerproducesatransparent“mesh”surface;thelatterproduces
anopaqueshadedone.Therearetwodifferentwaysofusingeachcommand,
oneforplottingsurfacesinwhichthezcoordinateisgivenasafunctionofx
and y, and one forparametricsurfaces in which x, y, and z are all given as
functionsoftwootherparameters.Letusillustratetheformerwithmeshand
thelatterwithsurf.
Toplotz= f(x, y),onebeginswitha meshgridcommandasinthecaseof
2 2
contour.Forexample,the“saddlesurface”z=x −y canbeplottedwith
X,Y = meshgrid(-2:.1:2, -2:.1:2);
Z = X.ˆ2 - Y.ˆ2;
mesh(X, Y, Z)
TheresultisshowninFigure5-6,althoughitlooksmuchbetteronthescreen
since MATLAB shades the surface with a color scheme depending on the z
coordinate.Wecouldhavegottenanopaquesurfaceinsteadbyreplacingmesh
withsurf.74 Chapter5: MATLABGraphics
4
3
2
1
0
-1
-2
-3
-4
2
1 2
1
0
0
-1
-1
-2
-2
Figure5-6
WiththeSymbolicMathToolbox,thereisashortcutcommandezmesh,
andyoucanobtainaresultverysimilartoFigure5-6with
ezmesh(’xˆ2 - yˆ2’, -2, 2, -2, 2)
If one wants to plot a surface that cannot be represented by an equation
2 2 2
oftheformz= f(x,y),forexamplethespherex +y +z =1,thenitisbet-
ter to parameterize the surface using a suitable coordinate system, in this
casecylindricalorsphericalcoordinates.Forexample,wecantakeasparam-
eters the vertical coordinatezand the polar coordinate θ in thex-y plane. If
r denotesthedistancetothezaxis,thentheequationofthespherebecomes
√ √ √
2 2 2 2 2
r +z =1, or r= 1−z , and so x= 1−z cosθ, y= 1−z sinθ. Thus
wecanproduceourplotwith
theta, Z = meshgrid((0:0.1:2)pi, (-1:0.1:1));
X = sqrt(1 - Z.ˆ2).cos(theta);SpecialEffects 75
1
0.5
0
-0.5
-1
1
0.5 1
0.5
0
0
-0.5
-0.5
-1
-1
Figure5-7
Y = sqrt(1 - Z.ˆ2).sin(theta);
surf(X, Y, Z); axis square
TheresultisshowninFigure5-7.
WiththeSymbolicMathToolbox,parametricplottingofsurfaceshas
beengreatlysimplifiedwiththecommands ezsurfandezmesh,andyoucan
obtainaresultverysimilartoFigure5-7with
ezsurf(’sqrt(1-sˆ2)cos(t)’, ’sqrt(1-sˆ2)sin(t)’, ...
’s’, -1, 1, 0, 2pi); axis equal
SpecialEffects
So far we have only discussed graphics commands that produce or modify a
singlestaticfigurewindow.ButMATLABisalsocapableofcombiningseveral76 Chapter5: MATLABGraphics
figures in one window, or of producing animated graphics that change with
time.
CombiningFiguresinOneWindow
The command subplot divides the figure window into an array of smaller
figures. The first two arguments give the dimensions of the array of sub-
plots, and the last argument gives the number of the subplot (counting left
torightacrossthefirstrow,thenlefttorightacrossthenextrow,andsoon)
inwhichtoputthenextfigure.Thefollowingexample,whoseoutputappears
asFigure5-8,producesa2×2arrayofplotsofthefirstfourBesselfunctions
J,0≤n≤3:
n
x = 0:0.05:40;
for j = 1:4, subplot(2,2,j)
plot(x, besselj(jones(size(x)), x))
end
1 0.6
0.4
0.5
0.2
0
0
-0.2
-0.5 -0.4
0 10 20 30 40 0 10 20 30 40
0.6 0.6
0.4 0.4
0.2 0.2
0 0
-0.2 -0.2
-0.4 -0.4
0 10 20 30 40 0 10 20 30 40
Figure5-8SpecialEffects 77
Animations
The simplest way to produce an animated picture is with comet, which pro-
duces a parametric plot of a curve (the way plot does), except that you can
seethecurvebeingtracedoutintime.Forexample,
t = 0:0.01pi:2pi;
figure; axis equal; axis(-1 1 -1 1); hold on
comet(cos(t), sin(t))
displaysuniformcircularmotion.
Formorecomplicatedanimations,youcanuse getframeand movie.The
command getframe captures the active figure window for one frame of the
movie, and movie then plays back the result. For example, the following (in
MATLAB5.3orlater—earlierversionsofthesoftwareusedaslightlydiffer-
entsyntax)producesamovieofavibratingstring:
x = 0:0.01:1;
for j = 0:50
plot(x, sin(jpi/5)sin(pix)), axis(0, 1, -2, 2)
M(j+1) = getframe;
end
movie(M)
It is worth noting that the axis command here is important, to ensure that
each frame of the movie is drawn with the same coordinate axes. (Other-
wise the scale of the axes will be different in each frame and the result-
ing movie will be totally misleading.) The semicolon after the getframe
command is also important; it prevents the spewing forth of a lot of nu-
merical data with each frame of the movie. Finally, make sure that while
MATLAB executes the loop that generates the frames, you do not cover the
activefigurewindowwithanotherwindow(suchastheCommandWindow).
Ifyoudo,thecontentsoftheotherwindowwillbestoredintheframesofthe
movie.
MATLAB6hasanewcommandmovieviewthatyoucanuseinplaceof
movietoviewtheanimationinaseparatewindow,withabuttontoreplay
themoviewhenitisdone.78 Chapter5: MATLABGraphics
CustomizingandManipulating
Graphics
Thisisamoreadvancedtopic;ifyouwishyoucanskipitonafirstreading.
So far in this chapter, we have discussed the most commonly used MATLAB
routinesforgeneratingplots.Butoften,togettheresultsonewants,oneneeds
to customize or manipulate the graphics these commands produce. Knowing
how to do this requires understanding a few basic principles concerning the
wayMATLABstoresanddisplaysgraphics.Formostpurposes,thediscussion
herewillbesufficient.Butifyouneedmoreinformation,youmighteventually
want to consult one of the books devoted exclusively to MATLAB graphics,
suchas UsingMATLABGraphics , which comes free (in PDF format) with
the software and can be accessed in the “MATLAB Manuals” subsection of
the “Printable Documentation” section in the Help Browser (or under “Full
DocumentationSet”fromthehelpdeskinMATLAB5.3andearlierversions),
orGraphicsandGUIswithMATLAB, 2nd ed., by P. Marchand, CRC Press,
BocaRaton,FL,1999.
In a typical MATLAB session, one may have many figure windows open
at once. However, only one of these can be “active” at any one time. One can
findoutwhichfigureisactivewiththecommand gcf, short for “get current
figure,”andonecanchangetheactivefigureto,say,figurenumber5withthe
commandfigure(5),orelsebyclickingonfigurewindow5withthemouse.
The command figure(withnoarguments)createsablankfigurewindow.
(Thisissometimesusefulifyouwanttoavoidoverwritinganexistingplot.)
Onceafigurehasbeencreatedandmadeactive,therearetwobasicwaysto
manipulateit.TheactivefigurecanbemodifiedbyMATLABcommandsinthe
commandwindow,suchasthecommands title and axis square that we
have already encountered. Or one can modify the figure by using the menus
and/ortoolsinthefigurewindowitself.Let’sconsiderafewexamples.Toinsert
labelsortextintoaplot,onemayusethecommandstext,xlabel,ylabel,
zlabel, and legend, in addition to title. As the names suggest, xlabel,
ylabel, and zlabel add text next to the coordinate axes, legend puts a
“legend”ontheplot,andtextaddstextataspecificpoint.Thesecommands
take various optional arguments that can be used to change the font family
andfontsizeofthetext.Asanexample,let’sillustratehowtomodifyourplot
ofthelemniscate(Figure5-3)byaddingandmodifyingtext:
figure(3)
title(’The lemniscate xˆ2-yˆ2=(xˆ2+yˆ2)ˆ2’,...CustomizingandManipulatingGraphics 79
2 2 2 2 2
The lemniscate x -y =(x +y )
1
0.8
0.6
0.4
0.2
0 ← a node, also an inflection
point for each branch
-0.2
-0.4
-0.6
-0.8
-1
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
x
Figure5-9
’FontSize’, 16, ’FontName’, ’Helvetica’,...
’FontWeight’, ’bold’)
text(0, 0, ’\leftarrow a node, also an inflection’)
text(0.2, -0.1, ’point for each branch’)
xlabel(’x’); ylabel(’y’)
TheresultisshowninFigure5-9.Notethatmanysymbols(anarrowpointing
to the left in this case) can be inserted into a text string by calling them
withnamesstartingwith \.(Ifyou’veusedthescientifictypesettingprogram
T X, you’ll recognize the convention here.) In most cases the names are self-
E
explanatory.Forexample,yougetaGreekπ bytyping\pi,asummationsign
bytypingeither\Sigma(foracapitalsigma)or\sum,andarrowspointing
invariousdirectionswith\leftarrow,\uparrow,andsoon.Formoredetails
and a complete list of available symbols, see the listing for “Text Properties”
intheHelpBrowser.
Analternativeistomakeuseofthetoolbaratthetopofthefigurewindow.
Thebuttonindicatedbytheletter“A”addstexttoafigure,andthemenuitem
y80 Chapter5: MATLABGraphics
Text Properties... in the Tools menu (in MATLAB 5.3), or else the menu
itemFigureProperties...intheEditmenu(inMATLAB6),canbeusedto
changethefontstyleandfontsize.
ChangeofViewpoint
Anothercommonandimportantwaytovaryagraphicistochangetheview-
pointin3-space.Thiscanbedonewiththecommandview,andalso(atleast
inMATLAB5.3andhigher)byusingtheRotate3DoptionintheToolsmenu
atthetopofthefigurewindow.Thecommandview(2)projectsafigureinto
the x-y plane (by looking down on it from the positive z axis), and the com-
mandview(3)viewsitfromthedefaultdirectionin3-space,whichisinthe
direction looking toward the origin from a point far out on the ray z=0.5t,
x=−0.5272t,y=−0.3044t,t 0.
➱ InMATLAB,anytwo-dimensionalplotcanbe“viewedin3D,”and
anythree-dimensionalplotcanbeprojectedintotheplane.Thus
Figure5-5above(thehelix),iffollowedbythecommandview(2),
producesacircle.
ChangeofPlotStyle
Anotherimportantwaytochangethestyleofgraphicsistomodifythecoloror
linestyleinaplotortochangethescaleontheaxes.Withinaplotcommand,
one can change the color of a graph, or plot with a dashed or dotted line, or
marktheplottedpointswithspecialsymbols,simplybyaddingastringasa
thirdargumentforeveryx-ypair.Symbolsforcolorsare ’y’foryellow, ’m’
for magenta, ’c’ for cyan, ’r’ for red, ’g’ for green, ’b’ for blue, ’w’ for
white,and’k’forblack.Symbolsforpointmarkersinclude’o’foracircle,
’x’ for an X-mark, ’+’ for a plus sign, and ’’ for a star. Symbols for line
stylesinclude’-’forasolidline,’:’foradottedline,and’’foradashed
line.Ifapointstyleisgivenbutnolinestyle,thenthepointsareplottedbut
no curve is drawn connecting them. The same methods work with plot3 in
placeofplot.Forexample,onecanproduceasolidredsinecurvealongwitha
dottedbluecosinecurve,markingallthelocalmaximumpointsoneachcurve
withadistinctivesymbolofthesamecolorastheplot,asfollows:
X = (-2:0.02:2)pi; Y1 = sin(X); Y2 = cos(X);
plot(X, Y1, ’r-’, X, Y2, ’b:’); hold on
X1 = -3pi/2 pi/2; Y3 = 1 1; plot(X1, Y3, ’r+’)
X2 = -2pi 0 2pi; Y4 = 1 1 1; plot(X2, Y4, ’b’)CustomizingandManipulatingGraphics 81
Herewewouldprobablywantthetickmarksonthex axislocatedatmul-
tiplesofπ.Thiscanbedonewiththesetcommandappliedtotheproperties
of the axes (and/or by selecting Edit :Axes Properties... in MATLAB 6,
or Tools :Axes Properties... in MATLAB 5.3). The command set is used
to change various properties of graphics. To apply it to “Axes”, it has to be
combinedwiththecommand gca, which stands for “get current axes”. The
code
set(gca, ’XTick’, (-2:2)pi, ’XTickLabel’,...
’-2pi-pi0pi2pi’)
in combination with the code above gets the current axes, sets the ticks on
thex axistogofrom−2π to2π inmultiplesofπ,andthenlabelstheseticks
thewayonewouldwant(ratherthanindecimalnotation,whichisuglyhere).
TheresultisshowninFigure5-10.Incidentally,youmightwonderhowtolabel
theticksas−2π,−π,etc.,insteadof-2pi,-pi,andsoon.Thisistrickierbut
youcandoitbytyping
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
-2pi -pi 0 pi 2pi
Figure5-1082 Chapter5: MATLABGraphics
set(gca, ’FontName’, ’Symbol’)
set(gca, ’XTickLabel’, ’-2p-p0p2p’)
sinceintheSymbolfont,π occupiestheslotheldbypintextfonts.
Full-FledgedCustomization
Whataboutchangestootheraspectsofaplot?Theusefulcommandsgetand
setcanbeusedtoobtainacompletelistofthepropertiesofagraphicswindow,
and then to modify them. These properties are arranged in a hierarchical
structure, identified by markers (which are simply numbers) calledhandles.
If you type get(gcf), you will “get” a (rather long) list of properties of the
currentfigure(whosenumberisreturnedbythefunctiongcf).Someofthese
mightread
Color = 0.8 0.8 0.8
CurrentAxes = 72.0009
PaperSize = 8.5 11
Children = 72.0009
HerePaperSizeisself-explanatory;Colorgivesthebackgroundcolorofthe
plot in RGB (red-green-blue) coordinates, where 0 0 0 is black and 1 1 1
is white. (0.8 0.8 0.8 is light gray.) Note that CurrentAxes and Children
in this example have the same value, the one-element vector containing the
funny-looking number 72.0009. This number would also be returned by the
command gca (“get current axes”); it is the handle to the axis properties of
theplot.ThefactthatthisalsoshowsupunderChildrenindicatesthatthe
axispropertiesare“children”ofthefigure,thisis,theylieoneleveldowninthe
hierarchicalstructure.Typingget(gca)orget(72.0009)wouldthengive
youalistofaxisproperties,includingfurtherChildrensuchas Lineobjects,
withinwhichyouwouldfindtheXDataandYDataencodingtheactualplot.
Once you have located the properties you’re interested in, they can be
changedwithset.Forexample,
set(gcf, ’Color’, 1 0 0)
changesthebackgroundcoloroftheborderofthefigurewindowtored,and
set(gca, ’Color’, 1 1 0)
changes the background color of the plot itself (a child of the figure window)
toyellow(whichintheRGBschemeishalfred,halfgreen).CustomizingandManipulatingGraphics 83
This “one at a time” method for locating and modifying figure properties
can be speeded up using the command findobj to locate the handles of all
the descendents (the main figure window, its children, children of children,
etc.)ofthecurrentfigure.Onecanalsolimitthesearchtohandlescontaining
elementsofaspecifictype.Forexample,findobj(’Type’, ’Line’)hunts
for all handles of objects containing a Line element. Once one has located
these, set can be used to change the LineStyle from solid to dashed, etc.
In addition, the low-level graphics commands line, rectangle, fill,
surface, and image can be used to create new graphics elements within a
figurewindow.
Asanexampleofthesetechniques,thefollowingcodecreatesachessboard
onawhitebackground,asshowninFigure5-11:
white = 1 1 1; gray = 0.7white;
a=0110;b=0011;c=1111;
Figure5-1184 Chapter5: MATLABGraphics
figure; hold on
for k = 0:1, for j = 0:2:6
fill(a’c + c’(0:2:6) + k, b’c+j+k, gray)
end, end
plot(8a’, 8b’, ’k’)
set(gca, ’XTickLabel’, , ’YTickLabel’, )
set(gcf, ’Color’, white); axis square
Here white and gray are the RGB codings for white and gray. The double
for loop draws the 32 dark squares on the chessboard, using fill, with j
indexingthedarksquaresinasingleverticalcolumn,withk=0givingthe
odd-numbered rows, and withk=1 giving the even-numbered rows. Note
thatfillheretakesthreearguments:amatrix,eachofwhosecolumnsgives
thexcoordinatesoftheverticesofapolygontobefilled(inthiscaseasquare),
a second matrix whose corresponding columns give the y coordinates of the
vertices, and a color. We’ve constructed the matrices with four columns, one
for each of the solid squares in a single horizontal row. The plot command
draws the solid black line around the outside of the board. Finally, the first
set command removes the printed labels on the axes, and the second set
commandresetsthebackgroundcolortowhite.
QuickPlotEditingintheFigureWindow
Almostallofthecommand-linechangesonecanmakeinafigurehavecoun-
terparts that can be executed using the menus in the figure window. So why
botherlearningbothtechniques?Thereasonisthateditinginthefigurewin-
dowisoftenmoreconvenient,especiallywhenonewishesto“experiment”with
various changes, while editing a figure with MATLAB code is often required
whenwritingM-files.SothetrueMATLABexpertusesbothtechniques.The
figurewindowmenusareabitdifferentinMATLAB6thaninMATLAB5.3.
InMATLAB6,youcanzoominandoutandrotatethefigureusingtheTools
menu,youcaninsertlabelsandtextwiththe Insertmenu,andyoucanview
and edit the figure properties (just as you would with set)withthe Edit
menu. For example you can change the ticks and labels on the axes by se-
lectingEdit:EditAxes....InMATLAB5.3,editingofthefigurepropertiesis
donewiththe Property Editor, located under the File menu of the figure
window.Bydefaultthisopenstothefigureproperties,anddouble-clickingon
“Children”thenenablesyoutoaccesstheaxesproperties,etc.Sound 85
Sound
You can use sound to generate sound on your computer (provided that your
computer is suitably equipped). Although, strictly speaking, sound is not a
graphicscommand,wehaveplaceditinthischaptersincewethinkof“sight”
and“sound”asbeingalliedfeatures.Thecommandsoundtakesavector,views
itasthewaveformofasound,and“plays”it.Thelengthofthevector,dividedby
8192,isthelengthofthesoundinseconds.A“sinusoidal”vectorcorresponds
toapuretone,andthefrequencyofthesinusoidalsignaldeterminesthepitch.
ThusthefollowingexampleplaysthemottofromBeethoven’s5thSymphony:
x=0:0.1pi:250pi; y=zeros(1,200); z=0:0.1pi:1000pi;
sound(sin(x),y,sin(x),y,sin(x),y,sin(z4/5),y,...
sin(8/9x),y,sin(8/9x),y,sin(8/9x),y,sin(z3/4));
Notethatthezerovectoryinthisexamplecreatesaveryshortpausebetween
successivenotes.PracticeSetB
Calculus,Graphics,
andLinearAlgebra
Problems2,3,5–7,andpartsof10–12requiretheSymbolicMathTool-
box.Theothersdonot.
1. Usecontourtodothefollowing:
3 3
(a) Plot the level curves of the function f(x,y)=3y+y −x in the
regionwherex andyarebetween−1and1(togetanideaofwhat
thecurveslooklikeneartheorigin),andinsomelargerregions(to
getthebigpicture).
3 3
(b) Plotthecurve3y+y −x =5.
(c) Plotthelevelcurveofthefunction f(x,y)=ylnx+xlnythatcon-
tainsthepoint(1,1).
2. Find the derivatives of the following functions. If possible, simplify each
answer.
3 2
(a) f(x)=6x −5x +2x−3.
2x−1
(b) f(x)= .
2
x +1
2
(c) f(x)=sin(3x +2).
(d) f(x)=arcsin(2x+3).
√
4
(e) f(x)= 1+x .
r
(f) f(x)=x .
2
(g) f(x)=arctan(x +1).
3. SeeifMATLABcandothefollowingintegralssymbolically.Fortheindef-
initeintegrals,checktheresultsbydifferentiating.
π/2
(a) cosxdx.
0
2
(b) xsin(x )dx.
√
(c) sin(3x) 1−cos(3x)dx.
86
Advise:Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.