MATLAB Basics

MATLAB Basics
GregDeamons Profile Pic
GregDeamons,New Zealand,Professional
Published Date:03-08-2017
Your Website URL(Optional)
Comment
Chapter2 MATLABBasics Inthischapter,youwillstartlearninghowtouseMATLABtodomathematics. You should read this chapter at your computer, with MATLAB running. Try thecommandsinaMATLABCommandWindowasyougoalong.Feelfreeto experimentwithvariantsoftheexampleswepresent;thebestwaytofindout howMATLABrespondstoacommandistotryit.  Forfurtherpractice,youcanworktheproblemsinPracticeSetA.The GlossarycontainsasynopsisofmanyMATLABoperators,constants, functions,commands,andprogramminginstructions. InputandOutput YouinputcommandstoMATLABintheMATLABCommandWindow.MAT- LAB returns output in two ways: Typically, text or numerical output is re- turned in the same Command Window, but graphical output appears in a separate graphics window. A sample screen, with both a MATLAB Desktop andagraphicswindow,labeledFigureNo.1,isshowninFigure2–1. Togeneratethisscreenonyourcomputer,firsttype1/2 + 1/3.Thentype ezplot(’xˆ3 - x’).  WhileMATLABisworking,itmaydisplaya“wait”symbol—forexample, anhourglassappearsonmanyoperatingsystems.Oritmaygivenovisual evidenceuntilitisfinishedwithitscalculation. Arithmetic As we have just seen, you can use MATLAB to do arithmetic as you would a calculator.Youcanuse“+”toadd,“-”tosubtract,“”tomultiply,“/”todivide, 8Arithmetic 9 Figure2-1: MATLABOutput. and“ˆ”toexponentiate.Forexample, 3ˆ2 - (5 + 4)/2 + 63 ans = 22.5000 MATLABprintstheanswerandassignsthevaluetoavariablecalledans. Ifyouwanttoperformfurthercalculationswiththeanswer,youcanusethe variable ans rather than retype the answer. For example, you can compute thesumofthesquareandthesquarerootofthepreviousanswerasfollows: ansˆ2 + sqrt(ans) ans = 510.9934 Observe that MATLAB assigns a new value to answitheachcalculation. Todomorecomplexcalculations,youcanassigncomputedvaluestovariables ofyourchoosing.Forexample, u = cos(10) u= -0.839110 Chapter2: MATLABBasics v = sin(10) v= -0.5440 uˆ2 + vˆ2 ans = 1 MATLABusesdouble-precisionfloatingpointarithmetic,whichisaccurate toapproximately15digits;however,MATLABdisplaysonly5digitsbydefault. To display more digits, type format long. Then all subsequent numerical outputwillhave15digitsdisplayed.Typeformat shorttoreturnto5-digit display. MATLAB differs from a calculator in that it can do exact arithmetic. For example,itcanaddthefractions1/2and1/3symbolicallytoobtainthecorrect fraction 5/6. We discuss how to do this in the sectionSymbolicExpressions, VariablePrecision,andExactArithmeticonthenextpage. Algebra UsingMATLAB’sSymbolicMathToolbox,youcancarryoutalgebraic orsymboliccalculationssuchasfactoringpolynomialsorsolvingalgebraic equations.Typehelp symbolictomakesurethattheSymbolicMathTool- boxisinstalledonyoursystem. Toperformsymboliccomputations,youmustusesymstodeclarethevari- ables you plan to use to be symbolic variables. Consider the following series ofcommands: syms x y (x - y)(x - y)ˆ2 ans = (x-y)3 expand(ans)Algebra 11 ans = x3-3x2y+3xy2-y3 factor(ans) ans = (x-y)3  Noticethatsymbolicoutputisleft-justified,whilenumericoutputis indented.Thisfeatureisoftenusefulindistinguishingsymbolicoutput fromnumericaloutput. Although MATLAB makes minor simplifications to the expressions you type,itdoesnotmakemajorchangesunlessyoutellitto.Thecommandex- pandtoldMATLABtomultiplyouttheexpression,andfactorforcedMAT- LABtorestoreittofactoredform. MATLABhasacommandcalledsimplify,whichyoucansometimesuse toexpressaformulaassimplyaspossible.Forexample, simplify((xˆ3 - yˆ3)/(x - y)) ans = x2+xy+y2  MATLABhasamorerobustcommand,calledsimple,thatsometimesdoes abetterjobthansimplify.Trybothcommandsonthetrigonometric expressionsin(x)cos(y) + cos(x)sin(y)tocompare—you’llhave toreadtheonlinehelpforsimpletocompletelyunderstandtheanswer. SymbolicExpressions,VariablePrecision,andExactArithmetic Aswehavenoted,MATLABusesfloatingpointarithmeticforitscalculations. UsingtheSymbolicMathToolbox,youcanalsodoexactarithmeticwithsym- bolicexpressions.Considerthefollowingexample: cos(pi/2) ans = 6.1232e-17 −17 The answer is written in floating point format and means 6.1232×10 . However, we know that cos(π/2) is really equal to 0. The inaccuracy is due to the fact that typing pi in MATLAB gives an approximation to π accurate12 Chapter2: MATLABBasics to about 15 digits, not its exact value. To compute an exact answer, instead of an approximate answer, we must create an exactsymbolic representation of π/2 by typing sym(’pi/2’). Now let’s take the cosine of the symbolic representationofπ/2: cos(sym(’pi/2’)) ans = 0 Thisistheexpectedanswer. Thequotesaroundpi/2insym(’pi/2’)createastringconsistingofthe characters pi/2 and prevent MATLAB from evaluating pi/2 as a floating pointnumber.Thecommandsymconvertsthestringtoasymbolicexpression. Thecommandssymandsymsarecloselyrelated.Infact,syms xisequiv- alenttox = sym(’x’).Thecommandsymshasalastingeffectonitsargu- ment(itdeclaresittobesymbolicfromnowon),whilesymhasonlyatempo- raryeffectunlessyouassigntheoutputtoavariable,asinx = sym(’x’). Hereishowtoadd1/2and1/3symbolically: sym(’1/2’) + sym(’1/3’) ans = 5/6 Finally,youcanalsodovariable-precisionarithmeticwithvpa.Forexample, √ toprint50digitsof 2,type vpa(’sqrt(2)’, 50) ans = 1.4142135623730950488016887242096980785696718753769 ➱ Youshouldbewaryofusingsymorvpaonanexpressionthat MATLABmustevaluatebeforeapplyingvariable-precision arithmetic.Toillustrate,entertheexpressions3ˆ45, vpa(3ˆ45), andvpa(’3ˆ45’).Thefirstgivesafloatingpointapproximationto theanswer,thesecond—becauseMATLABonlycarries16-digit precisioninitsfloatingpointevaluationoftheexponentiation— givesananswerthatiscorrectonlyinitsfirst16digits,andthe thirdgivestheexactanswer.  SeethesectionSymbolicandFloatingPointNumbersinChapter4fordetails abouthowMATLABconvertsbetweensymbolicandfloatingpointnumbers.ManagingVariables 13 ManagingVariables We have now encountered three different classes of MATLAB data: floating pointnumbers,strings,andsymbolicexpressions.InalongMATLABsession it may be hard to remember the names and classes of all the variables you havedefined.Youcantypewhostoseeasummaryofthenamesandtypesof yourcurrentlydefinedvariables.Here’stheoutputofwhosfortheMATLAB sessiondisplayedinthischapter: whos Name Size Bytes Class ans 1x1 226 sym object u 1x1 8 double array v 1x1 8 double array x 1x1 126 sym object y 1x1 126 sym object Grand total is 58 elements using 494 bytes We see that there are currently five assigned variables in our MATLAB session.Threeareofclass“symobject”;thatis,theyaresymbolicobjects.The variablesxandyaresymbolicbecausewedeclaredthemtobesousingsyms, andansissymbolicbecauseitistheoutputofthelastcommandweexecuted, which involved a symbolic expression. The other two variables, u and v, are of class “double array”. That means that they are arrays of double-precision numbers;inthiscasethearraysareofsize1×1(thatis,scalars).The“Bytes” columnshowshowmuchcomputermemoryisallocatedtoeachvariable. Try assigning u = pi, v = ’pi’, and w = sym(’pi’), and then type whostoseehowthedifferentdatatypesaredescribed. The command whos shows information about all defined variables, but it doesnotshowthevaluesofthevariables.Toseethevalueofavariable,simply typethenameofthevariableandpress ENTERor RETURN. MATLAB commands expect particular classes of data as input, and it is importanttoknowwhatclassofdataisexpectedbyagivencommand;thehelp textforacommandusuallyindicatestheclassorclassesofinputitexpects.The wrongclassofinputusuallyproducesanerrormessageorunexpectedoutput. Forexample,typesin(’pi’)toseehowunexpectedoutputcanresultfrom supplyingastringtoafunctionthatisn’tdesignedtoacceptstrings. Toclearalldefinedvariables,typeclearorclear all.Youcanalsotype, forexample,clear x ytoclearonlyxandy. You should generally clear variables before starting a new calculation. Otherwise values from a previous calculation can creep into the new14 Chapter2: MATLABBasics Figure2-2:DesktopwiththeWorkspaceBrowser. calculation by accident. Finally, we observe that theWorkspacebrowser pre- sents a graphical alternative to whos. You can activate it by clicking on the Workspace tab, by typing workspace at the command prompt, or through the View item on the menu bar. Figure 2-2 depicts a Desktop in which the CommandWindowandtheWorkspacebrowsercontainthesameinformation asdisplayedabove. ErrorsinInput Ifyoumakeanerrorinaninputline,MATLABwillbeepandprintanerror message.Forexample,here’swhathappenswhenyoutrytoevaluate3uˆ2: 3uˆ2 ??? 3u2 Error: Missing operator, comma, or semicolon. Theerrorisamissingmultiplicationoperator.Thecorrectinputwouldbe 3uˆ2. Note that MATLAB places a marker (a vertical line segment) at the placewhereitthinkstheerrormightbe;however,theactualerrormayhave occurredearlierorlaterintheexpression.OnlineHelp 15 ➱ Missingmultiplicationoperatorsandparenthesesareamongthe mostcommonerrors. Youcaneditaninputlinebyusingthe UP-ARROWkeytoredisplaythepre- vious command, editing the command using the LEFT- and RIGHT-ARROW keys, and then pressing RETURN or ENTER.TheUP- and DOWN-ARROW keys allow you toscrollbackandforththroughallthecommandsyou’vetypedinaMATLAB session, and are very useful when you want to correct, modify, or reenter a previouscommand. OnlineHelp ThereareseveralwaystogetonlinehelpinMATLAB.Togethelponaparticu- larcommand,enterhelpfollowedbythenameofthecommand.Forexample, help solvewilldisplaydocumentationfor solve.Unlessyouhavealarge monitor, the output of help solve will not fit in your MATLAB command window, and the beginning of the documentation will scroll quickly past the top of the screen. You can force MATLAB to display information one screen- fulatatimebytyping more on.Youpressthespacebartodisplaythenext screenful,or ENTERtodisplaythenextline;typehelp morefordetails.Typing more onaffectsallsubsequentcommands,untilyoutypemore off. The command lookfor searches the first line of every MATLAB help file for a specified string (use lookfor -alltosearchalllines).Forexample, if you wanted to see a list of all MATLAB commands that contain the word “factor” as part of the command name or brief description, then you would type lookfor factor. If the command you are looking for appears in the list,thenyoucanusehelponthatcommandtolearnmoreaboutit. The most robust online help in MATLAB 6 is provided through the vastly improvedHelpBrowser.TheHelpBrowsercanbeinvokedinseveralways:by typinghelpdeskatthecommandprompt,undertheViewiteminthemenu bar,orthroughthequestionmarkbuttononthetoolbar.Uponitslaunchyou will see a window with two panes: the first, called theHelpNavigator, used to find documentation; and the second, called the display pane, for viewing documentation. The display pane works much like a normal web browser. It hasanaddresswindow,buttonsformovingforwardandbackward(amongthe windowsyouhavevisited),livelinksformovingaroundinthedocumentation, thecapabilityofstoringfavoritesites,andothersuchtools. You use the Help Navigator to locate the documentation that you will ex- ploreinthedisplaypane.TheHelpNavigatorhasfourtabsthatallowyouto16 Chapter2: MATLABBasics arrangeyoursearchfordocumentationindifferentways.ThefirstistheCon- tents tab that displays a tree view of all the documentation topics available. Theextentofthattreewillbedeterminedbyhowmuchyou(oryoursystem administrator)includedintheoriginalMATLABinstallation(howmanytool- boxes, etc.). The second tab is anIndex that displays all the documentation available in index format. It responds to your key entry of likely items you wanttoinvestigateintheusualalphabeticreactionmode.Thethirdtabpro- vides the Search mechanism. You type in what you seek, either a function or some other descriptive term, and the search engine locates corresponding documentation that pertains to your entry. Finally, the fourth tab is a roster ofyourFavorites.Clickingonanitemthatappearsinanyofthesetabsbrings upthecorrespondingdocumentationinthedisplaypane. The Help Browser has an excellent tutorial describing its own operation. Toviewit,opentheBrowser;ifthedisplaypaneisnotdisplayingthe“Begin Here” page, then click on it in the Contents tab; scroll down to the “Using the Help Browser” link and click on it. The Help Browser is a powerful and easy-to-useaidinfindingtheinformationyouneedonvariouscomponentsof MATLAB.Likeanysuchtool,themoreyouuseit,themoreadeptyoubecome atitsuse.  IfyoutypehelpwintolaunchtheHelpBrowser,thedisplaypanewill containthesamerosterthatyouseeastheresultoftypinghelpatthe commandprompt,buttheentrieswillbelinks. VariablesandAssignments InMATLAB,youusetheequalsigntoassignvaluestoavariable.Forinstance, x=7 x= 7 willgivethevariablexthevalue7fromnowon.Henceforth,wheneverMAT- LABseestheletterx,itwillsubstitutethevalue7.Forexample,ifyhasbeen definedasasymbolicvariable,then xˆ2 - 2xy + y ans = 49-13ySolvingEquations 17 ➱ Toclearthevalueofthevariablex,typeclear x. You can make very general assignments for symbolic variables and then manipulatethem.Forexample, clear x; syms x y z = xˆ2 - 2xy + y z= x2-2xy+y 5yz ans = 5y(x2-2xy+y) A variable name or function name can be any string of letters, digits, and underscores,provideditbeginswithaletter(punctuationmarksarenotal- lowed).MATLABdistinguishesbetweenuppercaseandlowercaseletters.You shouldchoosedistinctivenamesthatareeasyforyoutoremember,generally using lowercase letters. For example, you might use cubicsol as the name ofthesolutionofacubicequation. ➱ Acommonsourceofpuzzlingerrorsistheinadvertentreuseof previouslydefinedvariables. MATLAB never forgets your definitions unless instructed to do so. You can checkonthecurrentvalueofavariablebysimplytypingitsname. SolvingEquations Youcansolveequationsinvolvingvariableswithsolveorfzero.Forexam- 2 ple,tofindthesolutionsofthequadraticequationx −2x−4=0,type solve(’xˆ2 - 2x-4=0’) ans = 5(1/2)+1 1-5(1/2) Note that the equation to be solved is specified as a string; that is, it is sur- roundedbysinglequotes.Theanswerconsistsoftheexact(symbolic)solutions18 Chapter2: MATLABBasics √ 1± 5. To get numerical solutions, type double(ans),or vpa(ans) to dis- playmoredigits. Thecommandsolvecansolvehigher-degreepolynomialequations,aswell asmanyothertypesofequations.Itcanalsosolveequationsinvolvingmore thanonevariable.Iftherearefewerequationsthanvariables,youshouldspec- ify(asstrings)whichvariable(s)tosolvefor.Forexample,typesolve(’2x - log(y) = 1’, ’y’) to solve 2x−logy=1 for y in terms of x. You can specifymorethanoneequationaswell.Forexample, x, y = solve(’xˆ2-y=2’,’y-2x=5’) x= 1+22(1/2) 1-22(1/2) y= 7+42(1/2) 7-42(1/2) Thissystemofequationshastwosolutions.MATLABreportsthesolutionby givingthetwoxvaluesandthetwoyvaluesforthosesolutions.Thusthefirst solution consists of the first value ofx together with the first value of y.You canextractthesevaluesbytypingx(1)andy(1): x(1) ans = 1+22(1/2) y(1) ans = 7+42(1/2) Thesecondsolutioncanbeextractedwithx(2)andy(2). Notethatintheprecedingsolvecommand,weassignedtheoutputtothe vector x, y.Ifyouuse solveonasystemofequationswithoutassigning theoutputtoavector,thenMATLABdoesnotautomaticallydisplaythevalues ofthesolution: sol = solve(’xˆ2-y=2’,’y-2x=5’)SolvingEquations 19 sol = x: 2x1 sym y: 2x1 sym Toseethevectorsofxandyvaluesofthesolution,typesol.xandsol.y.To seetheindividualvalues,typesol.x(1),sol.y(1),etc. Some equations cannot be solved symbolically, and in these cases solve triestofindanumericalanswer.Forexample, solve(’sin(x)=2-x’) ans = 1.1060601577062719106167372970301 Sometimesthereismorethanonesolution,andyoumaynotgetwhatyou expected.Forexample, solve(’exp(-x) = sin(x)’) ans = -2.0127756629315111633360706990971 +2.7030745115909622139316148044265i The answer is a complex number; the i at the end of the answer stands for √ thenumber −1.Thoughitisavalidsolutionoftheequation,therearealso realnumbersolutions.Infact,thegraphsofexp(−x)andsin(x)areshownin Figure 2-3; each intersection of the two curves represents a solution of the −x equatione =sin(x). You can numerically find the solutions shown on the graph with fzero, whichlooksforazeroofagivenfunctionnearaspecifiedvalueofx.Asolution −x −x oftheequatione =sin(x)isazeroofthefunctione −sin(x),sotofindthe solutionnearx=0.5type fzero(inline(’exp(-x) - sin(x)’), 0.5) ans = 0.5885 Replace0.5with3tofindthenextsolution,andsoforth.  Intheexampleabove,thecommandinline,whichwewilldiscussfurtherin thesectionUser-DefinedFunctionsbelow,convertsitsstringargumenttoa20 Chapter2: MATLABBasics exp(-x) and sin(x) 1 0.5 0 -0.5 -1 0 1 2 3 4 5 6 7 8 9 10 x Figure2-3 functiondataclass.Thisisthetypeofinputfzeroexpectsasitsfirst argument.  IncurrentversionsofMATLAB,fzeroalsoacceptsastringexpressionwith independentvariablex,sothatwecouldhaverunthecommandabove withoutusinginline,butthisfeatureisnolongerdocumentedinthehelp textforfzeroandmayberemovedinfutureversions. VectorsandMatrices MATLAB was written originally to allow mathematicians, scientists, and engineers to handle the mechanics of linear algebra — that is, vectors and matrices — as effortlessly as possible. In this section we introduce these concepts.VectorsandMatrices 21 Vectors Avectorisanorderedlistofnumbers.Youcanenteravectorofanylengthin MATLABbytypingalistofnumbers,separatedbycommasorspaces,inside squarebrackets.Forexample, Z = 2,4,6,8 Z= 2468 Y=4-35-281 Y= 4 -35-281 Suppose you want to create a vector of values running from 1 to 9. Here’s howtodoitwithouttypingeachnumber: X = 1:9 X= 123456789 Thenotation1:9isusedtorepresentavectorofnumbersrunningfrom1to 9 in increments of 1. The increment can be specified as the second of three arguments: X = 0:2:10 X= 0246810 You can also use fractional or negative increments, for example, 0:0.1:1 or 100:-1:0. The elements of the vector X can be extracted as X(1), X(2), etc. For ex- ample, X(3) ans = 422 Chapter2: MATLABBasics To change the vector X from a row vector to a column vector, put a prime (’) afterX: X’ ans = 0 2 4 6 8 10 Youcanperformmathematicaloperationsonvectors.Forexample,tosquare theelementsofthevectorX,type X.ˆ2 ans = 04163664100 The period in this expression is very important; it says that the numbers inXshouldbesquaredindividually,orelement-by-element.TypingXˆ2would tell MATLAB to use matrix multiplication to multiply X by itself and would produce an error message in this case. (We discuss matrices below and in Chapter 4.) Similarly, you must type . or ./ if you want to multiply or di- videvectorselement-by-element.Forexample,tomultiplytheelementsofthe vectorXbythecorrespondingelementsofthevectorY,type X.Y ans = 0 -6 20 -12 64 10 MostMATLABoperationsare,bydefault,performedelement-by-element. For example, you do not type a period for addition and subtraction, and you can type exp(X) to get the exponential of each number in X (the matrix ex- ponentialfunctionisexpm).OneofthestrengthsofMATLABisitsabilityto efficientlyperformoperationsonvectors.VectorsandMatrices 23 Matrices Amatrix is a rectangular array of numbers. Row and column vectors, which wediscussedabove,areexamplesofmatrices.Considerthe3×4matrix   1 234   A= 5 678 . 9101112 ItcanbeenteredinMATLABwiththecommand A = 1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12 A= 1234 5678 9101112 Notethatthematrixelementsinanyrowareseparatedbycommas,andthe rowsareseparatedbysemicolons.Theelementsinarowcanalsobeseparated byspaces. IftwomatricesAandBarethesamesize,their(element-by-element)sum isobtainedbytypingA+B.Youcanalsoaddascalar(asinglenumber)toa matrix;A+c adds ctoeachelementin A. Likewise,A-B represents the difference of A and B, andA-c subtracts the number cfromeachelement of A.If Aand Baremultiplicativelycompatible(thatis,if Aisn×mand Bis m×),thentheirproduct ABisn×.Recallthattheelementof ABinthe ithrowand jth column is the sum of the products of the elements from the ithrowof Atimestheelementsfromthe jthcolumnof B,thatis, m  (A∗B) = A B , 1≤i≤n, 1≤ j ≤. ij ik kj k=1 TheproductofanumbercandthematrixAisgivenbycA,andA’represents the conjugate transpose of A. (For more information, see the online help for ctransposeandtranspose.) A simple illustration is given by the matrix product of the 3×4 matrix A abovebythe4×1columnvectorZ’: AZ’ ans = 60 140 22024 Chapter2: MATLABBasics Theresultisa3×1matrix,inotherwords,acolumnvector. MATLABhasmanycommandsformanipulatingmatrices.Youcanread abouttheminthesectionMoreaboutMatricesinChapter4andintheonline help;someofthemareillustratedinthesectionLinearEconomicModelsin Chapter9. SuppressingOutput Typing a semicolon at the end of an input line suppresses printing of the output of the MATLAB command. The semicolon should generally be used when defining large vectors or matrices (such as X = -1:0.1:2;). It can also be used in any other situation where the MATLAB output need not be displayed. Functions InMATLAByouwillusebothbuilt-infunctionsaswellasfunctionsthatyou createyourself. Built-inFunctions MATLAB has many built-in functions. These include sqrt, cos, sin, tan, log, exp, and atan (for arctan) as well as more specialized mathematical functionssuchas gamma,erf,andbesselj.MATLABalsohasseveralbuilt- √ inconstants,includingpi(thenumber π),i(thecomplexnumberi= −1), andInf(∞).Herearesomeexamples: log(exp(3)) ans = 3 The function log is the natural logarithm, called “ln” in many texts. Now consider sin(2pi/3) ans = 0.8660Functions 25 Togetanexactanswer,youneedtouseasymbolicargument: sin(sym(’2pi/3’)) ans = 1/23(1/2) User-Defined Functions Inthissectionwewillshowhowtouseinlinetodefineyourownfunctions. 2 Here’showtodefinethepolynomialfunction f(x)=x +x+1: f = inline(’xˆ2+x+1’, ’x’) f= Inline function: f(x)=x2+x+1 The first argument to inline is a string containing the expression defining the function. The second argument is a string specifying the independent variable.  Thesecondargumenttoinlinecanbeomitted,inwhichcaseMATLABwill “guess”whatitshouldbe,usingtherulesabout“DefaultVariables”tobe discussedlaterattheendofChapter4. Oncethefunctionisdefined,youcanevaluateit: f(4) ans = 21 MATLAB functions can operate on vectors as well as scalars. To make an inlinefunctionthatcanactonvectors,weuseMATLAB’svectorizefunction. 2 Hereisthevectorizedversionof f(x)=x +x+1: f1 = inline(vectorize(’xˆ2+x+ 1’), ’x’) f1 = Inline function: f1(x) = x.2+x+126 Chapter2: MATLABBasics Notethathasbeenreplacedby..Nowyoucanevaluatef1onavector: f1(1:5) ans = 37132131 Youcanplotf1,usingMATLABgraphics,inseveralwaysthatwewillexplore in the next section. We conclude this section by remarking that one can also definefunctionsoftwoormorevariables: g = inline(’uˆ2 + vˆ2’, ’u’, ’v’) g= Inline function: g(u,v) = u2+v2 Graphics In this section, we introduce MATLAB’s two basic plotting commands and showhowtousethem. Graphingwithezplot The simplest way to graph a function of one variable is with ezplot, which expectsastringorasymbolicexpressionrepresentingthefunctiontobeplot- 2 ted.Forexample,tographx +x+1ontheinterval−2to2(usingthestring formofezplot),type ezplot(’xˆ2+x+1’,-22) Theplotwillappearonthescreeninanewwindowlabeled“FigureNo.1”. Wementionedthatezplotacceptseitherastringargumentorasymbolic expression.Usingasymbolicexpression,youcanproducetheplotinFigure2-4 withthefollowinginput: syms x ezplot(xˆ2+x+1,-22)  Graphscanbemisleadingifyoudonotpayattentiontotheaxes.For example,theinputezplot(xˆ2+x+3,-22)producesagraphGraphics 27 2 x + x + 1 7 6 5 4 3 2 1 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 x Figure2-4 thatlooksidenticaltothepreviousone,exceptthattheverticalaxishas differenttickmarks(andMATLABassignsthegraphadifferenttitle). ModifyingGraphs Youcanmodifyagraphinanumberofways.Youcanchangethetitleabove the graph in Figure 2-4 by typing (in the Command Window, not the figure window) title ’A Parabola’ Youcanaddalabelonthehorizontalaxiswithxlabelorchangethelabel on the vertical axis with ylabel. Also, you can change the horizontal and vertical ranges of the graph with axis. For example, to confine the vertical rangetotheintervalfrom1to4,type axis(-2 2 1 4) Thefirsttwonumbersaretherangeofthehorizontalaxis;bothrangesmust

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.