axis(equal)A =arg=0:0.1: pi155exp(5)1:10nulltraceDisclaimerUnder no circumstances does the author assume anyresponsibility and liability thereof, for any injury caused to thereader by toxic fumes and explosions resulting from mixingincompatible matrices and vectors. Array operations are known tocause irritability and minor itching to beginners. The author,however, might buy the reader a cup of coffee in the case ofserious distress. In rare cases of very flattering comments or verycreative suggestions about improving this book, the author mighteven buy the reader lunch. The reader is encouraged to try his/herluck by sending comments to pratap@mecheng.iisc.ernet.in orrp28@cornell.eduTo Ma Gayatriand my parentsShri Chandrama Singh andSmt. Bachcha SinghContentsPreface 11 Introduction 31.1 What IsMATLAB? . . . . . . . . . . . . . . . . . . . . . . . 31.2 DoesMATLAB Do Symbolic Calculations? . . . . . . . . . . 51.3 WillMATLAB Run on My Computer? . . . . . . . . . . . . . 61.4 Where DoI Get MATLAB? . . . . . . . . . . . . . . . . . . . 61.5 How Do IUse This Book? . . . . . . . . . . . . . . . . . . . . 61.6 Basicsof MATLAB . . . . . . . . . . . . . . . . . . . . . . . 81.6.1MATLAB windows . . . . . . . . . . . . . . . . . . . . 81.6.2On-line help . . . . . . . . . . . . . . . . . . . . . . . . 91.6.3Input-Output . . . . . . . . . . . . . . . . . . . . . . . 91.6.4File types . . . . . . . . . . . . . . . . . . . . . . . . .121.6.5 Platform dependence . . . . . . . . . . . . . . . . . . .121.6.6 General commands you should remember . . . . . . . 151.7Visit This Again . . . . . . . . . . . . . . . . . . . . . . . . .162 Tutorial Lessons 192.1 Lesson 1: A Minimum MATLAB Session . . .. . . . . . . . . 212.2 Lesson 2: Working with Arrays of Numbers .. . . . . . . . . 252.3 Lesson 3: Creating and Printing SimplePlots . . . . . . . . . 292.4 Lesson 4: Creating, Saving, andExecuting a Script File . . . 332.5 Lesson 5: Creating andExecuting a Function File . . . . . . 372.6 Lesson 6: Working withFiles and Directories . . . . . . . . . 423 Interactive Computation473.1 Matrices and Vectors . . . . . . . . . . . . . . . . . . . .. . . 493.1.1 Input . . . . . . . . . . . . . . . . . . . . . . . .. . . 493.1.2 Indexing (or Subscripting) . . . . . . . . . . . . .. . . 503.1.3 Matrix Manipulation . . . . . . . . . . . . . . . . .. . 523.1.4 Creating Vectors . . . . . . . . . . . . . . . . . . .. . 553.2 Matrix and Array Operations . . . . . . . . . . . . . . .. . . 57ii CONTENTS3.2.1 Arithmetic operations . . . . . . . . . .. . . . . . . . 573.2.2 Relational operations . . . . . . . . . . .. . . . . . . . 593.2.3 Logical operations . . . . . . . . . . . .. . . . . . . . 593.2.4 Elementary math functions . . . . . . . . .. . . . . . 613.2.5 Matrix functions . . . . . . . . . . . . . . .. . . . . . 633.2.6 Character strings . . . . . . . . . . . . . . .. . . . . . 633.3 Creating and Using Inline Functions . . . . . . .. . . . . . . 673.4 Using Built-in Functions and On-line Help . . .. . . . . . . . 693.4.1 Example1: Finding the determinant of amatrix . . . 713.4.2 Example2: Finding eigenvalues and eigenvectors. . . 723.5 Saving and Loading Data . . . . . . . . . . . . . . . .. . . . 743.5.1 Saving into and loading from the binary Mat-les . .. 743.5.2 Importing Data Files . . . . . . . . . . . . . . . . . .. 753.5.3 Recording a session with diary . . . . . . . . . . . . .753.6 Plotting simple graphs . . . . . . . . . . . . . . . . . . .. . . 764 Programming in MATLAB: Scripts and Functions 854.1 ScriptFiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . 854.2Function Files . . . . . . . . . . . . . . . . . . . . . . . . . .. 884.2.1 Executing a function . . . . . . . . . . . . . . . . . .. 894.2.2 More on functions . . . . . . . . . . . . . . . . . . . .924.2.3 Subfunctions . . . . . . . . . . . . . . . . . . . . . . .954.2.4 Compiled (Parsed) functions: P-Code . . . . . . . . .954.2.5 The Proler . . . . . . . . . . . . . . . . . . . . . . . .964.3 Language-Specic Features . . . . . . . . . . . . . . . . . .. 964.3.1 Use of comments to create on-line help . . . . . . . .964.3.2 Continuation . . . . . . . . . . . . . . . . . . . . . . .974.3.3 Global variables . . . . . . . . . . . . . . . . . . . . .974.3.4 Loops, branches, and control-ow . . . . . . . . . . . .984.3.5 Interactive input . . . . . . . . . . . . . . . . . . . . .1014.3.6 Recursion . . . . . . . . . . . . . . . . . . . . . . . .. 1034.3.7 Input/output . . . . . . . . . . . . . . . . . . . . . .. 1044.4 Advanced Data Objects . . . . . . . . . . . . . . . . . .. . . 1054.4.1 Multidimensional matrices . . . . . . . . . . . . .. . . 1054.4.2 Structures . . . . . . . . . . . . . . . . . . . . .. . . . 1064.4.3 Cells . . . . . . . . . . . . . . . . . . . . . .. . . . . . 1105 Applications 1175.1 Linear Algebra . . . . . . . .. . . . . . . . . . . . . . . . . . 1175.1.1 Solving a linearsystem . . . . . . . . . . . . . . . . . 1175.1.2 Gaussianelimination . . . . . . . . . . . . . . . . . . . 1185.1.3 Findingeigenvalues & eigenvectors . . . . . . . . . . . 1195.1.4Matrix factorizations . . . . . . . . . . . . . . . . . .120CONTENTS iii5.1.5 Advanced topics . . . . . . . . . . . . . . .. . . . . . 1215.2 Curve Fitting and Interpolation . . . . . . . .. . . . . . . . . 1225.2.1 Polynomial curve tting on a y . . . . .. . . . . . . 1225.2.2 Do it yourself: curve tting using polynomialfunctions 1245.2.3 Least squares curve tting . . . . . . . . . . .. . . . . 1265.2.4 General nonlinear ts . . . . . . . . . . . . . .. . . . 1305.2.5 Interpolation . . . . . . . . . . . . . . . . . .. . . . . 1305.3 Data Analysis and Statistics . . . . . . . . . . .. . . . . . . . 1325.4 Numerical Integration (Quadrature) . . . . .. . . . . . . . . 1355.4.1 Double integration . . . . . . . . . . .. . . . . . . . . 1385.5 Ordinary Dierential Equations . . . . . .. . . . . . . . . . . 1405.5.1 Example1: A rst-order linear ODE . .. . . . . . . . 1415.5.2 Example2: A second-order nonlinear ODE . .. . . . 1425.5.3 ode23 versus ode45 . . . . . . . . . . . . . . . .. . . 1455.5.4 Specifying tolerance . . . . . . . . . . . . . . . .. . . 1455.5.5 The ODE Suite . . . . . . . . . . . . . . . . . . .. . . 1465.5.6 Event location . . . . . . . . . . . . . . . . . . .. . . 1485.6 Nonlinear Algebraic Equations . . . . . . . . . . . .. . . . . 1525.7 Advanced Topics . . . . . . . . . . . . . . . . .. . . . . . . . 1546 Graphics 1596.1 Basic 2-D Plots . . . . . . .. . . . . . . . . . . . . . . . . . . 1596.1.1 Style options . . .. . . . . . . . . . . . . . . . . . . . 1606.1.2 Labels, title,legend, and other text objects . . . . . . 1606.1.3 Axis control,zoom-in, and zoom-out . . . . . . . . . . 1616.1.4 Modifying plotswith Plot Editor . . . . . . . . . . . . 1626.1.5 Overlay plots . .. . . . . . . . . . . . . . . . . . . . . 1636.1.6 Specialized 2-Dplots . . . . . . . . . . . . . . . . . . . 1676.2 Using subplot toLayout Multiple Graphs . . . . . . . . . . . 1736.3 3-D Plots . . .. . . . . . . . . . . . . . . . . . . . . . . . . . 1736.3.1 View .. . . . . . . . . . . . . . . . . . . . . . . . . . . 1746.3.2Rotate view . . . . . . . . . . . . . . . . . . . . . . . .1776.3.3 Mesh and surface plots . . . . . . . . . . . . . . . . . .1776.3.4 Vector eld and volumetric plots . . . . . . . . . . . .1866.3.5 Interpolated surface plots . . . . . . . . . . . . . . . .1886.4 Handle Graphics . . . . . . . . . . . . . . . . . . . . . .. . . 1906.4.1 The object hierarchy . . . . . . . . . . . . . . . .. . . 1916.4.2 Object handles . . . . . . . . . . . . . . . . . . .. . . 1916.4.3 Object properties . . . . . . . . . . . . . . . . .. . . . 1926.4.4 Modifying an existing plot . . . . . . . . . . . .. . . . 1976.4.5 Complete control over the graphics layout . . . .. . . 1996.5 Saving and Printing Graphs . . . . . . . . . . . . . .. . . . . 202iv CONTENTS6.6 Animation . . . . . . . . . . . . . . .. . . . . . . . . . . . . . 2047 Errors 2118 What Else is There?2178.1 The Symbolic Math Toolbox . . . . . . . . . . . . . . . . .. 2178.1.1 Should you buy it? . . . . . . . . . . . . . . . . . . .. 2188.1.2 Two useful tools in the Symbolic Math Toolbox . . . .2188.1.3 Getting help with the Symbolic Toolbox . . . . . . . .2208.1.4 Using the Symbolic Math Toolbox . . . . . . . . . . .2218.1.5 Summary: some Symbolic Math Toolbox commands . 2248.2Debugging Tools . . . . . . . . . . . . . . . . . . . . . . . . .2258.3 External Interface: Mex-les . . . . . . . . . . . . . . . .. . . 2258.4 Graphics User Interface . . . . . . . . . . . . . . .. . . . . . 225A The MATLAB Language Reference 227A.1 PunctuationMarks and Other Symbols . . . . . . . . . . . . 227A.2General-Purpose Commands . . . . . . . . . . . . . . . . . . .229A.3 Special Variables and Constants . . . . . . . . . . . . . .. . . 230A.4 Language Constructs and Debugging . . . . . . . . . .. . . . 230A.5 File I/O . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . 230A.6 Operators and Logical Functions . . . . . .. . . . . . . . . . 231A.7 Math Functions . . . . . . . . . . . . .. . . . . . . . . . . . . 232A.8 Matrices: Creation &Manipulation . . . . . . . . . . . . . . . 233A.9 Character StringFunctions . . . . . . . . . . . . . . . . . . . 234A.10 GraphicsFunctions . . . . . . . . . . . . . . . . . . . . . . . . 234A.11Applications Functions . . . . . . . . . . . . . . . . . . . . . .236A.11.1 Data analysis and Fourier transforms . . . . . . . . . .236A.11.2 Polynomials and data interpolation . . . . . . . . . . .236A.11.3 Nonlinear numerical methods . . . . . . . . . . . . . .236PrefaceI enjoy MATLAB, and I want you to enjoy it toothat is thesingular moti-vation behind this book. The rst and foremost goal ofthis book is to getyou started in MATLAB quickly andpleasantly.Learning MATLAB changed the meaning of scienticcomputing for me.I used to think in terms of machine-speciccompilers and tables of numbersas output. Now, I expect and enjoyinteractive calculation, programming,graphics, animation, andcomplete portability across platformsall underone roof. MATLAB issimple, powerful, and for most purposes quite fast.This is not tosay that MATLAB is free of quirks and annoyances. It is notacomplete miracle drug, but I like it and I think you will probablylike it too.I rst used MATLAB in 1988 in a course on matrixcomputation taughtby Tom Coleman at Cornell University. We used theoriginal 1984 com-mercial version of MATLAB. Although the graphicscapability was limited tobare-bones 2-D plots, and programming wasnot possible on the mainframeVAX, I still loved it. After that Iused MATLAB in every course I took. Idid all the computations formy Ph.D. dissertation in nonlinear dynamicsusing MATLAB. Since thenI have used MATLAB in every engineering andmathematics course Ihave taught. I have enthusiastically tried to teachMATLAB to myfriends, colleagues, students, and my 4-year-old daughter.I havegiven several introductory lectures, demonstrations, andhands-onworkshops. This book is a result of my involvement withMATLAB teaching,both informal and in the class room, over the lastseveral years.This book is intended to get you started quickly.After an hour or twoof getting started you can use the book as areference. There are manyexamples, which you can modify for yourown use. The coverage of topicsis based on my experience of what ismost useful, and what I wish I couldhave found in a book when I waslearning MATLAB. If you nd the bookinformative and useful, it is mypleasure to be of service to you. If you ndit frustrating, pleaseshare your frustrations with me so that I can try toimprove futureeditions.The current edition has been updated for MATLAB 6. Thisupdate re-quired checking each command and function given in thisbook as examples,and changing them if required. Several newfeatures have been added thatare new in MATLAB 6. New versions ofsoftware packages usually add fea-tures that their experiencedusers ask for. As a result, the packages and their2 Prefacemanualsget bigger and bigger, and more intimidating to a new user. Ihavetried hard to protect the interests of a new user in this book.It has beena struggle to keep this book lean and thin, friendly tobeginners, and yetadd more features and applications. In responseto emails I have receivedfrom several readers across the globe, Ihave added more exercises in thisedition. I have also addedsubstantial material in Chapter 3 (InteractiveComputation) andChapter 5 (Applications).Acknowledgments.I was helped through thedevelopment of this book by the encouragement,criticism, editing,typing, and test-learning of many people, especially atCornellUniversity and the Indian Institute of Science. I thank allstudentswho have used this book in its past forms and providedconstructive criticism.I have also been fortunate to receivefeedback by email, sometimes quiteattering, from several readersall over the world. I greatly appreciate yourwords ofencouragement.I wish to thank Chris Wohlever, Mike Coleman, RichardRand, DavidCaughey, Yogendra Simha, Vijay Arakeri, Greg Couillard,Christopher D.Hall, James R. Wohlever, John T. Demel, Jerey L.Cipolla, John C. Polk-ing, Thomas Vincent, John Gibson, Sai JaganMohan, Konda Reddy, SeshaSai, Yair Hollander, Les Axelrod, RaviBhusan Singh Pandaw, Gujjarappa,Manjula, The MathWorks Inc., andCranes Software International for thehelp and support they haveextended to me in the development of this book.In addition, I mustacknowledge the help of three special people. Andy Ruinahas been anintegral part of the development of this book all along. In fact,hehas written most of Chapter 8, the introduction to the SymbolicMathToolbox. That apart, his criticisms and suggestions haveinuenced everypage of this book. Shishir Kumar has checked allcommands and programsfor compatibility with MATLAB 6, and has addedseveral examples. My ed-itor Peter Gordon at Oxford UniversityPress has always been supportiveand kept his word on keeping theprice of the book low.Lastly, I thank my wife, Kalpana, for beingincredibly supportive through-out. The rst edition of this bookcame out in 1995, just after our daughter,Manisha, was born. Shelearned to pronounce MATLAB at the age of two.Now that she hasgraduated to recognizing the MATLAB prompt and doingsimple integercalculations in MATLAB, a new batch of absolute beginnershasarrived twin boys Manas and Mayank. Despite their arrival, ifthisedition of the book is in your hands, it is because of my wifewho providedme with the time to work on the book by shoulderingmore than her fairshare of family responsibilities.Thank youall.Bangalore Rudra Pratap.May, 2001.1. Introduction1.1 What IsMATLAB?MATLABTMis a software package for high-performance numericalcomputa-tion and visualization. It provides an interactiveenvironment with hundredsof built-in functions for technicalcomputation, graphics, and animation.Best of all, it also provideseasy extensibility with its own high-level pro-gramming language.The name MATLAB stands for MATrix LABoratory.The diagram in Fig.1.1 shows the main features and capabilities ofMATLAB. MATLABsbuilt-in functions provide excellent tools for linear alge-bracomputations, data analysis, signal processing, optimization,numericalsolution of ordinary dierential equations (ODEs),quadrature, and manyother types of scientic computations. Most ofthese functions use state-of-the art algorithms. There are numerousfunctions for 2-D and 3-D graphicsas well as for animation. Also,for those who cannot do without their Fortranor C codes, MATLABeven provides an external interface to run those pro-grams fromwithin MATLAB. The user, however, is not limited to thebuilt-infunctions; he can write his own functions in the MATLABlanguage. Oncewritten, these functions behave just like thebuilt-in functions. MATLABslanguage is very easy to learn and touse.There are also several optional Toolboxes available from thedevelopersof MATLAB. These Toolboxes are collections of functionswritten for specialapplications such as Symbolic Computation, ImageProcessing, Statistics,Control System Design, Neural Networks,etc.The basic building block of MATLAB is the matrix. Thefundamentaldata-type is the array. Vectors, scalars, real matricesand complex matricesare all automatically handled as special casesof the basic data-type. What ismore, you almost never have todeclare the dimensions of a matrix. MATLABsimply loves matrices andmatrix operations. The built-in functions are4IntroductionGraphicsComputationsExternal Interface(Mex-files)(Collections of Specialized Functions) MATLAB 2-DGraphics 3-D Graphics Color and Lighting Animation Interface with Cand Fortran ProgramsBuilt-in FunctionsUser-written Functions SignalProcessing Image Processing Statistics Splines Control SystemRobust Control System Identification m-Analysis & SynthesisNeural Networks Optimization Communications Financial SymbolicMathematics (Maple inside) Linear Algebra Data Analysis SignalProcessing Polynomials & Interpolation Quadrature Solution ofODEs E X T R A $ F U N C T I O N S E X T R A $ F U N C T I O NSToolboxesMatlab Programming LanguageRAnd Many MoreFigure 1.1: Aschematic diagram of MATLABs main features.1.2 Does MATLAB DoSymbolic Calculations? 5optimized for vector operations.Consequently, vectorized1. commands orcodes run much faster inMATLAB.1.2 Does MATLAB Do Symbolic Calculations?(MATLAB vsMathematica, Maple, and Macsyma)If you are new to MATLAB, you arelikely to ask this question. The rst thingto realize is that MATLABis primarily a numerical computation package, al-though with theSymbolic Toolbox (standard with the Student Edition ofMATLAB. SeeSection 8.1 on page 217 for an introduction) it can do sym-bolicalgebra 2. Mathematica, Maple, and Macsyma are primarilysymbolicalgebra packages. Of course, they do numerical computationstoo. In fact,if you know any of these packages really well, you cando almost every calcu-lation that MATLAB does using that software.So why learn MATLAB? Well,MATLABs ease of use is its best feature.Also, it has a shallow learningcurve (more learning with less eort)while the computer algebra systemshave a steep learning curve.Since MATLAB was primarily designed to donumerical calculations andcomputer algebra systems were not, MATLAB isoften much faster atthese calculationsoften as fast as C or Fortran. Thereare otherpackages, such as Xmath, that are also closer in aim and scopebutseem to be popular with people in some specialized applicationareas.The bottom line is, in numerical computations, especiallythose that utilizevectors and matrices, MATLAB beats everyone handsdown in terms of easeof use, availability of built-in functions,ease of programming, and speed.The proof is in the phenomenalgrowth of MATLAB users around the worldin just a few years. Thereare more than 2000 universities and thousands ofcompanies listed asregistered users. MATLABs popularity today has forcedsuch powerfulpackages as Mathematica and Macsyma to provide extensionsfor les inMATLABs format!1Vectorization refers to a manner of computation inwhich an operation is performedsimultaneously on a list of numbers(a vector) rather than sequentially on each memberof the list. Forexample, let be a list of 100 numbers. Then y = sin() is avectorizedstatement as opposed to y1 = sin(1), y2 = sin(2),etc.2Symbolic algebra means that computation is done in terms ofsymbols or variablesrather than numbers. For example, if you type(x+y)^2 on your computer and the com-puter responds by saying thatthe expression is equal to x2+2xy +y2, then your computerdoessymbolic algebra. Software packages that do symbolic algebra arealso known asComputer Algebra Systems.6 Introduction1.3 Will MATLABRun on My Computer?The most likely answer is yes, because MATLABsupports almost everycomputational platform. In addition toWindows, MATLAB 6 is available forAIX, Digital UNIX, HP UX(including UX 10, UX 11), IRIX, IRIX64, Linux,and Solaris operatingsystems. Older versions of MATLAB are available foradditionalplatforms such as Mac OS, and Open VMS. To nd out moreabout productavailability for your particular computer, see theMathWorkshomepage on the website given below.1.4 Where Do I GetMATLAB?MATLAB is a product of the MathWorks, Incorporated. Contactthe com-pany for product information and ordering at the followingaddress:The MathWorks Inc.3 Apple Hill Drive, Natick, MA01760-2098Phone: (508) 647-7000, Fax: (508) 647-7001.Email:info@mathworks.comWorld Wide Web: HowDo I Use This Book?This book is intended to serve as anintroduction to MATLAB. The goal is toget started as simply aspossible. MATLAB is a very powerful and sophisti-cated package. Ittakes a while to understand its real power. Unfortunately,mostpowerful packages tend to be somewhat intimidating to abeginner.That is why this book exists to help you overcome thefear, get startedquickly, and become productive in very littletime. The most useful and eas-ily accessible features of MATLAB arediscussed rst to make you productiveand build your condence.Several features are discussed in sucient depth,with an invitationto explore the more advanced features on your own. Allfeatures arediscussed through examples using the following conventions:Typographical styles: All actual MATLAB commands or instructionsare shown in typedface. Place holders for variables or names in acommand are shown initalics. So, a command shown as help topicimplies that youhave to type the actual name of a topic in place oftopic in thecommand. Italic text has also been used to emphasize apoint and sometimes,to introduce a new term.Edited by FoxitReaderCopyright(C) by Foxit Corporation,2005-2009For EvaluationOnly.1.5 How Do I Use This Book? 7 Actual examples: Actual examplescarried out in MATLAB are shownin gray, shaded boxes. Explanatorynotes have been added within smallwhite rectangles in the grayboxes as shown below.>> >> 2+2ans = 4>> area =pi*2.15^2area = 14.5220MATLAB promptMATLAB responseCommandFigure1.2: Actual examples carried out in MATLAB are shown in grayboxesthroughout this book. The texts in the white boxes inside thesegrayboxes are explanatory notes.These gray, boxed gures areintended to provide a parallel track for theimpatient reader. Ifyou would rather try out MATLAB right away, youare encouraged to gothrough these boxed examples. Most of the ex-amples are designed sothat you can (more or less) follow them withoutreading the entiretext. All examples are system-independent. Aftertrying out theexamples, you should read the appropriate sections. On-line help:We encourage the use of on-line help. For almost allmajor topics,we indicate the on-line help category in a small box inthe marginas shown here.For on-line helptype:help helpTyping help category inMATLAB with the appropriate categoryname provides a list offunctions and commands in that category.Detailed help can then beobtained for any of those commands andfunctions.We discourage apassive reading of this book. The best way to learnany computersoftware is to try it out. We believe this, practice it,andencourage you to practice it too. So, if you are impatient,quickly readSections 1.6.11.6.3, jump to the tutorials on page 19,and get going.8 Introduction1.6 Basics of MATLABHere we discusssome basic features and commands. To begin, let us lookat thegeneral structure of the MATLAB environment.1.6.1 MATLAB windowsOnalmost all systems, MATLAB works through three basic windows,whichare shown in Fig. 1.3 and discussed below.1. Command window:This is the main window. It is characterized bythe MATLAB commandprompt . When you launch the applicationprogram, MATLAB puts you inthis window. All commands, includ-ing those for runninguser-written programs, are typed in this windowat the MATLABprompt. In MATLAB 6, this window is a part of theMATLAB window (seeFig. 1.3) that contains four other smaller win-dows. If you can getto the command window, we advise you to ignorethe other foursubwindows at this point. As software packages, suchas MATLAB,become more and more powerful, their creators add moreand morefeatures to address the needs of experienced users. Unfor-tunately,it makes life harder for the beginners there is more roomforconfusion, distraction, and intimidation. Although, we describetheother subwindows here that appear with the command window, wedonot expect it to be useful to you till you get to Lesson 6 inChapter 2.Launch Pad: This subwindow lists all MATLAB relatedapplicationsand toolboxes that are installed on your machine. Youcan launchany of the listed applications by double clicking onthem.Workspace: This subwindow lists all variables that you havegen-erated so far and shows their type and size. You can dovariousthings with these variables, such as plotting, by clickingon a vari-able and then using the right button on the mouse toselect youroption.Command History: All commands typed on the MATLABpromptin the command window get recorded, even across multipleses-sions (you worked on Monday, then on Thursday, and then onnextWednesday, and so on), in this window. You can select acommand fromthis window with the mouse and execute it in thecommand window bydouble clicking on it. You can also selecta set of commands fromthis window and create an M-le withthe right click of the mouse(and selecting the appropriate optionfrom the menu).CurrentDirectory: This is where all your les from the current di-rectoryare listed. You can do le navigation here. You also have1.6 Basicsof MATLAB 9several options of what you can do with a le once youselect it(with a mouse click). To see the options, click the rightbuttonof the mouse after selecting a le. You can run M-les,renamethem, delete them, etc.2. Graphics window: The output of allgraphics commands typed inthe command window are ushed to thegraphics or Figure window, aseparate gray window with (default)white background color. The usercan create as many gure windows asthe system memory will allow.3. Edit window: This is where youwrite, edit, create, and save yourown programs in les called M-les.You can use any text editor tocarry out these tasks. On mostsystems, MATLAB provides its ownbuilt-in editor. However, you canuse your own editor by typing thestandard le-editing command thatyou normally use on your system.From within MATLAB , the command istyped at the MATLAB promptfollowing the special character !. Theexclamation character promptsMATLAB to return the controltemporarily to the local operating sys-tem, which executes thecommand following the ! character. After theediting is completed,the control is returned to MATLAB. For example,on Unix systems,typing !vi myprogram.m at the MATLAB prompt(and hitting the returnkey at the end) invokes the vi editor on thele myprogram.m. Typing!emacs myprogram.m invokes the emacseditor.1.6.2 On-line helpOn-line documentation: MATLAB provides on-line help for allitsbuilt-in functions and programming language constructs. Thecom-mands lookfor, help, helpwin, and helpdesk provide on-linehelp.See Section 3.4 on page 69 for a description of the helpfacility. Demo: MATLAB has a demonstration program that shows manyof itsfeatures. The program includes a tutorial introduction thatis worthtrying. Type demo at the MATLAB prompt to invoke thedemonstrationprogram, and follow the instructions on thescreen.1.6.3 Input-OutputMATLAB supports interactive computation(see Chapter 3), taking the inputfrom the screen, and ushing theoutput to the screen. In addition, it canread input les and writeoutput les (see Section 4.3.7). The followingfeatures hold for allforms of input-output: Data type: The fundamental data-type inMATLAB is the array.It encompasses several distinct data objectsintegers, doubles (realEdited by Foxit ReaderCopyright(C) by FoxitCorporation,2005-2009For Evaluation Only.10 IntroductionMATLABWindow Figure WindowEdit WindowCommand WindowFigure 1.3: The MATLABenvironment consists of a Command Window, aFigure Window, and anEdit Window. The Figure and the Editor windowsappear only wheninvoked with the appropriate commands.1.6 Basics of MATLAB11numbers), matrices, character strings, structures, and cells. 3Inmostcases, however, you never have to worry about the data-type orthedata object declarations. For example, there is no need todeclarevariables as real or complex. When a real number is enteredas thevalue of a variable, MATLAB automatically sets the variableto be real(double). Dimensioning: Dimensioning is automatic inMATLAB. No dimen-sion statements are required for vectors orarrays. You can nd thedimensions of an existing matrix or a vectorwith the size and length(for vectors only) commands. Casesensitivity: MATLAB is case-sensitive; that is, itdierentiatesbetween the lowercase and uppercase letters. Thus a andA are dierentvariables. Most MATLAB commands and built-in functioncalls aretyped in lowercase letters. You can turn case sensitivityon and owith the casesen command. However, we do not recommend it.Output display: The output of every command is displayed onthescreen unless MATLAB is directed otherwise. A semicolon at theendof a command suppresses the screen output, except for graphicsandon-line help commands. The following facilities are provided forcon-trolling the screen output : Paged output: To direct MATLAB toshow one screen of outputat a time, type more on at the MATLABprompt. Without it,MATLAB ushes the entire output at once, withoutregard to thespeed at which you read. Output format: Thoughcomputations inside MATLAB are per-formed using double precision,the appearance of oating pointnumbers on the screen is controlledby the output format in use.There are several dierent screen outputformats. The followingtable shows the printed value of 10 in 7dierent formats.format short 31.4159format short e3.1416e+001format long 31.41592653589793format long e3.141592653589793e+001format short g 31.416format long g31.4159265358979format hex 403f6a7a2955385eformat rat3550/113format bank 31.423Structures and cells are new data objectsintroduced in MATLAB 5. See Section 4.4on page 105 for theirdescription. MATLAB 5.x also allows users to create their owndataobjects and associated operations. We do not discuss thisfacility in this book.12 IntroductionThe additional formats, formatcompact and format loose, con-trol the spacing above and below thedisplayed lines, and format+ displays a +, -, and blank forpositive, negative, and zero num-bers, respectively. The default isformat short. The displayformat is set by typing format type on thecommand line (seeFig. 2.1 on page 22 for an example). Commandhistory: MATLAB saves previously typed commands ina buer. Thesecommands can be recalled with the up-arrow key(). This helps inediting previous commands. You can also recall aprevious command bytyping the rst few characters and then pressingthe key.Alternatively, you can copy and paste commands fromthe CommandHistory subwindow where all your commands fromeven previoussessions of MATLAB are recorded and listed. On mostUnix systems,MATLABs command-line editor also understands thestandard emacskeybindings.1.6.4 File typesMATLAB has three types of les forstoring information:M-les are standard ASCII text les, with a .mextension to the lename.There are two types of these les: scriptles and function les (seeSection 4.1 and 4.2). Most programs youwrite in MATLAB are savedas M-les. All built-in functions in MATLABare M-les, most of whichreside on your computer in precompiledformat. Some built-in func-tions are provided with source code inreadable M-les so that theycan be copied and modied.Mat-les arebinary data-les, with a .mat extension to the lename. Mat-les arecreated by MATLAB when you save data with the save com-mand. Thedata is written in a special format that only MATLAB canread.Mat-les can be loaded into MATLAB with the load command(see Section3.5 for details.).Mex-les are MATLAB-callable Fortran and Cprograms, with a .mex ex-tension to the lename. Use of these lesrequires some experiencewith MATLAB and a lot of patience. We donot discuss Mex-les inthis introductory book.1.6.5 PlatformdependenceOne of the best features of MATLAB is itsplatform-independence. Once youare in MATLAB, for most part, itdoes not matter which computer you areon. Almost all commands workthe same way. The only commands thatdier are the ones thatnecessarily depend on the local operating system,1.6 Basics ofMATLAB 13such as editing (if you do not use the built-in editor)and saving M-les.Programs written in the MATLAB language workexactly the same way onall computers. The user interface (how youinteract with your computer),however, may vary a little fromplatform to platform. Launching MATLAB : If MATLAB is installed onyour machine cor-rectly then you can launch it by following thesedirections:On PCs: Navigate and nd the MATLAB folder, locate theMATLABprogram, and double-click on the program icon to launchMATLAB.If you have worked in MATLAB before and have an M-le orMat-lethat was written by MATLAB, you can also double-click on thele tolaunch MATLAB.On Unix machines: Type matlab on the Unix promptand hit re-turn. If MATLAB is somewhere in your path, it will belaunched. If itis not, ask your system administrator. Creating adirectory and saving les: Where should you save yourles so thatMATLAB can easily access them? In MATLAB 6, there is adefaultfolder called work where MATLAB saves your les if you donot specifyany other location. If you are the only user of MATLAB onthecomputer you are working on, this is ne. You can save all yourworkin this folder and access all your les easily (default set-up).Ifnot, you have to create a separate folder for saving yourwork.Theoretically, you can create a directory/folder anywhere,save yourles, and direct MATLAB to nd those les. The mostconvenientplace, however, to save all user-written les is in adirectory (or folder)immediately below the directory (or folder) inwhich the MATLAB ap-plication program is installed (for PCs). Thisway all user-written lesare automatically accessible to MATLAB. Ifyou need to store the lessomewhere else, you might have to specifythe path to the les usingthe path command, or change the workingdirectory of MATLAB to thedesired directory with the cd command. Werecommend the latter.On PCs: Create a folder inside the MATLABfolder and save your lesthere. If you are not allowed to write inthe MATLAB folder (as may bethe case in some shared facilities),then create a folder where you areallowed (perhaps on your own oppydisk), copy the le startup.m (ifit exists4) from theMATLAB/Toolbox/local folder to your folder,and launch MATLAB bydouble-clicking on the startup.m le in yourfolder. This way MATLABautomatically accesses all les in your folder.You should alsopersonalize the Startup le by editing it and addinga line, say,disp(Hello Kelly, Welcome Aboard.) You can open,4If it does notexist, then create one using MATLAB and save it in your folder.14Introductionwrite, and save M-les by selecting appropriate commandsfrom theFile menu in MATLAB.On Unix machines: Create a directoryfor your MATLAB work, saveall MATLAB related les here, and launchMATLAB from this directory.To open, write, and save M-les, use atext editor such as vi or emacs.You can also use the built-ineditor if you are working in MATLAB 5.2or later versions.Printing:On PCs: To print the contents of the current active window(com-mand, gure, or edit window), select Print... from the Filemenu andclick Print in the dialog box. You can also print thecontents of thegure window by typing print at the MATLAB prompt.OnUnix machines: To print a le from inside MATLAB, typetheappropriate Unix command preceded by the exclamation character(!).For example, to print the le startup.m, type !lpr startup.monthe MATLAB prompt. To print a graph that is currently in thegurewindow simply type print on the MATLAB prompt.1.6 Basics ofMATLAB 151.6.6 General commands you should rememberOn-line helphelplists topics on which help is availablehelpwin opens theinteractive help windowhelpdesk opens the web browser based helpfacilityhelp topic provides help on topiclookfor string lists helptopics containing stringdemo runs the demo programWorkspaceinformationwho lists variables currently in the workspacewhos listsvariables currently in the workspace with their sizewhat lists m-,mat-, and mex-les on the diskclear clears the workspace, allvariables are removedclear x y z clears only variables x, y andzclear all clears all variables and functions from workspacemlockfun locks function fun so that clear cannot remove itmunlock fununlocks function fun so that clear can remove itclc clears commandwindow, command history is losthome same as clcclf clears gurewindowDirectory informationpwd shows the current workingdirectorycd changes the current working directorydir lists contentsof the current directoryls lists contents of the current directory,same as dirpath gets or sets MATLAB search patheditpath modiesMATLAB search pathcopyfile copies a lemkdir creates adirectoryGeneral informationcomputer tells you the computer typeyou are usingclock gives you wall clock time and date as avectordate tells you the date as a stringmore controls the pagedoutput according to the screen sizever gives the license and theversion information about MATLABinstalled on your computerbenchbenchmarks your computer on running MATLABcompared to othercomputers16 IntroductionTermination^c (Control-c) local abort,kills the current command executionquit quits MATLABexit same asquit1.7 Visit This AgainWe would like to point out a few thingsthat vex the MATLAB beginners,perhaps, the most. Although, many ofthese things would probably notmake sense to you right now, theyare here, and you can come back to themwhenever they seemrelevant.In the past, le navigation in MATLAB has causedconsiderable problemto users, especially the beginners. We have hadnumerous complaints fromstudents about not being able to makeMATLAB nd their le, get MATLABto work from their directory, getMATLAB to nd and execute the currentlyedited le, etc. Fortunately,MATLAB 6 has incorporated some new featuresthat mitigate thisproblem immensely. The Current Directory is shownjust above theCommand Window with the option of changing the currentdirectorywith just a click of the mouse. In addition, there is aCurrentDirectory subwindow to the left of the Command Window thatlists les inthe current directory, gives you options of opening,loading (a .mat le),executing (a .m le), editing, etc., with theclick of the right button onthe mouse. You can also change thedirectory there or add a particulardirectory to the MATLAB path sothat MATLAB has access to all the les inthat directoryautomatically.If you do not save all your MATLAB les in the defaultWork directory orfolder, you need to be aware of the followingissues.1. Not being in the right directory: You may write and savemanyMATLAB programs (M-les) but MATLAB does not seem to nd them.Ifyour les are not in the current working directory, MATLABcannotaccess them. Find which directory you are currently in bylookingat the small Current Directory window in the toolbar or byqueryingMATLAB with the command pwd. Use dir or ls at thecommandprompt to see if MATLAB lists your les or click on theCurrent Direc-tory tab to the left of the command window to see thelisting of lesin that subwindow. If you do not see your les, guideMATLAB to getto the directory where your les are. Use cd or path;cd is easier touse but applies only to the current session. Withpath command, youcan save the path to your directory and haveMATLAB automaticallyaccess your directory every time you use it.Use the on-line help to seehow to set the path. Also, see Lesson-6in the tutorials (Chapter 2).1.7 Visit This Again 172. Not savingles in the correct directory: When you edit a le inthe MATLABEditor/Debugger Window, and save it, it does not au-tomaticallymean that MATLAB Command Window has access to thedirectory yousaved your le in. So, after saving the le, when you tryto executeit and MATLAB does not nd your le, go to the item (1.)above and setthings right.3. Not overwriting an existing le while editing: Yourun your pro-gram by executing your M-le, do not like the result,edit the le,and run it again; but MATLAB gives the same answer! Thepreviouslyparsed (compiled) le is executing, MATLAB does not knowabout yourchanges. This can happen due to various reasons. Simplecure is, clearthe workspace with clear all and execute yourle.There are various other little things that cause trouble fromtime to time.We point them out throughout the book wherever theyraise their head.2. TutorialLessonsThe following lessons aredesigned to get you started quickly in MATLAB.Each lesson shouldtake about 1015 minutes. The lessons are intended tomake youfamiliar with the basic facilities of MATLAB. We urge you also todothe exercises given at the end of each lesson. This will take moretime,but it will teach you quite a few things. If you get stuck inthe exercises,simply turn the page; answers are on the back. Mostanswers consist ofcorrect commands to do the exercises. But thereare several correct waysof doing the problems. So, your commandsmight look dierent than thosegiven.Before You StartYou need someinformation about the computer you are going to work on.Inparticular, nd out: How to switch on the computer and get itstarted. How to log on and log o. Where MATLAB is installed on thecomputer. How to access MATLAB. Where you can write and saveleshard drive or a oppy disk. If there is a printer attached to thecomputer.If you are working on your own computer, you will mostlikely know theanswer to these questions. If you are working on acomputer in a publicfacility, the system manager can help you. Ifyou are in a class that requiresworking on MATLAB, your professoror TA can provide answers. In publicfacilities, sometimes the bestthing to do is to spot a friendly person workingthere and ask thesequestions politely. People are usually nice!20 Tutorial LessonsIfyou have not read the introduction (Chapter 1), we recommendthatyou at least read Sections 1.6.11.6.3 and glance through therest of Sec-tion 1.6 before trying the tutorials.Here are thelessons in a nutshell:Lesson-1: Launch MATLAB, do some simplecalculations, and quit.Key features: Learn to add, multiply, andexponentiate numbers, usetrig functions, and control screen outputwith format.Lesson-2: Create and work with arrays, vectors inparticular.Key features: Learn to create, add, and multiplyvectors, use sin andsqrt functions with vector arguments, and uselinspace to create avector.Lesson-3: Plot simple graphs.Keyfeatures: Learn to plot, label, and print out a circle.Lesson-4:Write and execute a script le.Key features: Learn to write, save,and execute a script le that plotsa unit circle.Lesson-5: Write andexecute a function le.Key features: Learn to write, save, andexecute a function le thatplots a circle of any speciedradius.Lesson-6: Learn about le and directory navigation.Keyfeatures: Learn several ways of checking your currentdirectory,changing working directory, and setting MATLAB path.2.1Lesson 1: A Minimum MATLAB Session 212.1 Lesson 1: A Minimum MATLABSessionGoal: To learn how to log on, invoke MATLAB, do a fewtrivial calculations,quit MATLAB, and log o.Time Estimates:Lesson:10 minutesExercises: 30 minutesWhat you are going to learn: How todo simple arithmetic calculations. The arithmetic operatorsare:+addition, subtraction, multiplication,/ division, andexponentiation. How to assign values to variables. How to suppressscreen output. How to control the appearance of oating pointnumbers on the screen. How to quit MATLAB.The MATLABcommands/operators used are+, -, *, /, ^, ;sin, cos,logformatquitIn addition, if you do the exercises, you will learnmore about arith-metic operations, exponentiation and logarithms,trigonometric functions,and complex numbers.Method: Log on andlaunch MATLAB. Once the MATLAB command win-dow is on the screen,you are ready to carry out the rst lesson. Somecommands and theiroutput are shown below. Go ahead and reproduce theresults.22Tutorial LessonsEnter 2+2 and hit return/enter key.Note that theresult of an un-assigned expression is saved in the defaultvariable ans.You can also assign the value ofan expression to avariable.A semicolon at the end suppressesscreen output. MATLABremembersy, though. You can recall the value of y by simply typingy.MATLAB knows trigonometry.Here is arccosine of -1.The floatingpoint output displayis controlled by the format command. Here aretwo examples.More info on this later.Quit MATLAB. You can alsoquitby selecting quit from the file menu on Macs and PCs. >>2+2ans = 4>> x = 2+2x = 4>> y = 2^2 +log(pi)*sin(x);>> yy = 3.1337>> theta = acos(-1)theta =3.1416>> format short e>> thetatheta =3.1416e+000>> format long>> thetatheta =3.14159265358979>> quitFigure 2.1: Lesson-1: Some simplecalculations in MATLAB.2.1 Lesson 1: A Minimum MATLAB Session23EXERCISES1. Arithmetic operations: Compute the followingquantities: 25251 and compare with (1 125)1. 351(5+1)2 1. Thesquare root x can be calculated with thecommand sqrt(x) or x^0.5.Area = r2with r = 13 1. ( is pi in MATLAB.)2. Exponential andlogarithms: The mathematical quantities ex, lnx,and log x arecalculated with exp(x), log(x), and log10(x), respec-tively.Calculate the following quantities: e3, ln(e3), log10(e3), andlog10(105). e163. Solve 3x= 17 for x and check the result. (Thesolution is x = ln 17ln 3 .You can verify the result by directsubstitution.)3. Trigonometry: The basic MATLAB trig functions aresin, cos,tan, cot, sec, and csc. The inverses, e.g., arcsin,arctan, etc., arecalculated with asin, atan, etc. The same is truefor hyperbolicfunctions. The inverse function atan2 takes 2arguments, y and x,and gives the four-quadrant inverse tangent. Theargument of thesefunctions must be in radians.Calculate thefollowing quantities: sin 6, cos , and tan 2. sin2 6 + cos2 6.(Typing sin^2(x) for sin2x will produce an er-ror). y = cosh2xsinh2x, with x = 32.4. Complex numbers: MATLAB recognizes theletters i and j as theimaginary number 1. A complex number 2 + 5imay be input as2+5i or 2+5*i in MATLAB . The former case is alwaysinterpreted asa complex number whereas the latter case is taken ascomplex only ifi has not been assigned any local value. The same istrue for j. Thiskind of context dependence, for better or worse,pervades MATLAB.Compute the following quantities. 1+3i13i. Can youcheck the result by hand calculation? ei4. Check the Eulers Formulaeix= cos x+i sinx by computingthe right hand side too, i. e.,compute cos(/4) + i sin(/4). Execute the commands exp(pi/2*i) andexp(pi/2i). Can youexplain the dierence between the two results?24Tutorial LessonsAnswers to Exercises1. Command Result2^5/(2^5-1)1.03233*(sqrt(5)-1)/(sqrt(5)+1)^2 - 1 -0.6459area=pi*(pi^(1/3)-1)^20.67812. Command Resultexp(3) 20.0855log(exp(3))3.0000log10(exp(3)) 1.3029log10(10^5) 5.0000exp(pi*sqrt(163))2.6254e+017x=log(17)/log(3) 2.57893. Command Resultsin(pi/6)0.5000cos(pi) -1.0000tan(pi/2)1.6332e+016(sin(pi/6))^2+(cos(pi/6))^2 1x=32*pi;y=(cosh(x))^2-(sinh(x))^2 04. Command Result(1+3i)/(1-3i) -0.8000 +0.6000iexp(i*pi/4) 0.7071 + 0.7071iexp(pi/2*i) 0.0000 +1.0000iexp(pi/2i) 0.0000 - 1.0000iNote thatexp(pi/2*i)= e2 i=cos(2) + i sin(2) = iexp(pi/2i)= e2i = e2 i= cos(2) i sin(2) = i2.2Lesson 2: Working with Arrays of Numbers 252.2 Lesson 2: Creatingand Working with Arraysof NumbersGoal: To learn how to createarrays and vectors, and how to performarithmetic and trigonometricoperations on them.An array is a list of numbers or expressionsarranged in horizontal rows and verticalcolumns. When an array hasonly one row or column, it is called a vector. An arraywith m rowsand n columns is a called a matrix of size m n. See Section 3.1 formoreinformation.Time Estimates:Lesson: 15 minutesExercises: 45minutesWhat you are going to learn: How to create row and columnvectors. How to create a vector of n numbers linearly (equally)spaced betweentwo given numbers a and b. How to do simplearithmetic operations on vectors. How to do array operations:.*term by term multiplication,./ term by term division, and.^ term byterm exponentiation. How to use trigonometric functions with arrayarguments. How to use elementary math functions such as squareroot, exponen-tials, and logarithms, with array arguments.Thislesson deals primarily with one-dimensional arrays, i.e.,vectors.One of the exercises introduces you to two-dimensionalarrays, i.e., matrices.There are many mathematical conceptsassociated with vectors and matricesthat we do not mention here. Ifyou have some background in linear algebra,you will nd that MATLABis set up to do almost any matrix computation(e.g., inverse,determinant, rank, etc.).Method: You already know how to launchMATLAB. So go ahead andtry the commands shown on the next page.Once again, you are going toreproduce the results shown.26 TutorialLessons>> x = [1 2 3]x = 1 2 3 >> y = [2; 1; 5]y = 2 15 >> z = [2 1 0];>> a = x + za = 3 3 3 >> b = x +y??? Error using ==> +Matrix dimensions must agree.>> a =x.*za = 2 2 0 >> b = 2*ab = 4 4 0 >> x =linspace(0,10,5)x = 0 2.5000 5.0000 7.5000 10.0000 >> y =sin(x);>> z = sqrt(x).*yz = 0 0.9463 -2.1442 2.5688-1.7203You can multiply (or divide) the elements of two same-sizedvectors term by term with the array operator .* (or ./). But youcannot add (or subtract) a row vector to a column vector.x is a rowvector with 3 elements.y is a column vector with 3 elements.You canadd (or subtract) two vectors of the same size. But multiplying avector with a scalar does not need any special operation (no dotbefore the *).Create a vector x with 5 elementslinearly spacedbetween 0 and 10.Trigonometric functions sin, cos,etc., as well aselementary mathfunctions sqrt, exp, log, etc., operate on vectorsterm by term.Figure 2.2: Lesson-2: Some simple calculations withvectors.2.2 Lesson 2: Working with Arrays of Numbers 27EXERCISES1.Equation of a straight line: The equation of a straight line is y =mx +cwhere m and c are constants. Compute the y-coordinates of aline with slopem = 0.5 and the intercept c = 2 at the followingx-coordinates:x = 0, 1.5, 3, 4, 5, 7, 9, and 10.[Note: Your commandshould not involve any array operators since your cal-culationinvolves multiplication of a vector with a scalar m and thenadditionof another scalar c.]2. Multiply, divide, and exponentiatevectors: Create a vector t with 10elements: 1, 2, 3, . . ., 10. Nowcompute the following quantities: x = t sin(t). y = t1t+1. z =sin(t2)t2 .3. Points on a circle:All points with coordinates x = rcos and y = r sin,where r is a constant, lie on a circle withradius r, i.e., they satisfy theequation x2+ y2= r2. Create acolumn vector for with the values 0, /4,/2, 3/4, , and 5/4.Take r =2 and compute the column vectors x and y. Now check that x andyindeed satisfy the equation of circle, by computing the radius r =_(x2+ y2).[To calculate r you will need the array operator .^ forsquaring x and y. Ofcourse, you could compute x2by x.*x also.]4.The geometric series: This is funky! You know how to computexnelement-by-element for a vector x and a scalar exponent n. Howabout com-puting nx, and what does it mean? The result is again avector with elementsnx1, nx2, nx3etc.The sum of a geometric series1 +r +r2+r3+. . . +rnapproaches the limit11r for r >theta = linspace(0,2*pi,100);>> x = cos(theta);>> y =sin(theta);>> plot(x,y)>> axis('equal');>>xlabel('x')>> ylabel('y')>> title('Circle of unitradius')>> printCreate a linearly spaced 100 elements longvector theta.Calculate x and y coordinates.Plot x vs. y. (seeSection 6.1)Set the length scales of the twoaxes to be thesame.Label the x-axis with x.Label the y-axis with y.Put a title onthe plot.Print on the default printer.Figure 2.3: Lesson-3:Plotting and printing a simple graph.Comments: After you enter thecommand plot(x,y), you should see an ellipse inthe Figure Window.MATLAB draws an ellipse rather than a circle be-cause of itsdefault rectangular axes. The next command axis(equal),directsMATLAB to use the same scale on both axes, so that a circleappearsas a circle. You can also use axis(square) to override thedefaultrectangular axes. The arguments of the axis, xlabel, ylabel, andtitle commandsare text strings. Text strings are entered withinsingle right-quote (
Rudra Pratap Matlab Ebook Pdf Download
2ff7e9595c
コメント