Primer MATLAB

2y ago
26 Views
2 Downloads
2.23 MB
210 Pages
Last View : 15d ago
Last Download : 3m ago
Upload by : Aliana Wahl
Transcription

MATLAB PrimerR2017b

How to Contact MathWorksLatest news:www.mathworks.comSales and services:www.mathworks.com/sales and servicesUser community:www.mathworks.com/matlabcentralTechnical support:www.mathworks.com/support/contact usPhone:508-647-7000The MathWorks, Inc.3 Apple Hill DriveNatick, MA 01760-2098MATLAB Primer COPYRIGHT 1984–2017 by The MathWorks, Inc.The software described in this document is furnished under a license agreement. The software may beused or copied only under the terms of the license agreement. No part of this manual may be photocopiedor reproduced in any form without prior written consent from The MathWorks, Inc.FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentationby, for, or through the federal government of the United States. By accepting delivery of the Program orDocumentation, the government hereby agrees that this software or documentation qualifies ascommercial computer software or commercial computer software documentation as such terms are used ordefined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms andconditions of this Agreement and only those rights specified in this Agreement, shall pertain to and governthe use, modification, reproduction, release, performance, display, and disclosure of the Program andDocumentation by the federal government (or other entity acquiring for or through the federalgovernment) and shall supersede any conflicting contractual terms or conditions. If this License fails tomeet the government's needs or is inconsistent in any respect with federal procurement law, thegovernment agrees to return the Program and Documentation, unused, to The MathWorks, Inc.TrademarksMATLAB and Simulink are registered trademarks of The MathWorks, Inc. Seefor a list of additional trademarks. Other product or brandnames may be trademarks or registered trademarks of their respective ks products are protected by one or more U.S. patents. Please seewww.mathworks.com/patents for more information.

Revision HistoryDecember 1996May 1997September 1998September 2000June 2001July 2002August 2002June 2004October 2004March 2005June 2005First printingSecond printingThird printingFourth printingOnline onlyOnline onlyFifth printingSixth printingOnline onlyOnline onlySeventh printingSeptember 2005Online onlyMarch 2006Online onlySeptember 2006Eighth printingMarch 2007Ninth printingSeptember 2007Tenth printingMarch 2008Eleventh printingOctober 2008Twelfth printingMarch 2009Thirteenth printingSeptember 2009Fourteenth printingMarch 2010Fifteenth printingSeptember 2010April 2011September 2011March 2012Sixteenth printingOnline onlySeventeenth printingEighteenth printingSeptember 2012March 2013September 2013March 2014October 2014March 2015September 2015March 2016September 2016March 2017September 2017Nineteenth printingTwentieth printingTwenty-first printingTwenty-second printingTwenty-third printingTwenty-fourth printingTwenty-fifth printingTwenty-sixth printingTwenty-seventh printingTwenty-eighth printingTwenty-ninth printingFor MATLAB 5For MATLAB 5.1For MATLAB 5.3Revised for MATLAB 6 (Release 12)Revised for MATLAB 6.1 (Release 12.1)Revised for MATLAB 6.5 (Release 13)Revised for MATLAB 6.5Revised for MATLAB 7.0 (Release 14)Revised for MATLAB 7.0.1 (Release 14SP1)Revised for MATLAB 7.0.4 (Release 14SP2)Minor revision for MATLAB 7.0.4 (Release14SP2)Minor revision for MATLAB 7.1 (Release14SP3)Minor revision for MATLAB 7.2 (Release2006a)Minor revision for MATLAB 7.3 (Release2006b)Minor revision for MATLAB 7.4 (Release2007a)Minor revision for MATLAB 7.5 (Release2007b)Minor revision for MATLAB 7.6 (Release2008a)Minor revision for MATLAB 7.7 (Release2008b)Minor revision for MATLAB 7.8 (Release2009a)Minor revision for MATLAB 7.9 (Release2009b)Minor revision for MATLAB 7.10 (Release2010a)Revised for MATLAB 7.11 (R2010b)Revised for MATLAB 7.12 (R2011a)Revised for MATLAB 7.13 (R2011b)Revised for Version 7.14 (R2012a)(Renamed from MATLAB Getting StartedGuide)Revised for Version 8.0 (R2012b)Revised for Version 8.1 (R2013a)Revised for Version 8.2 (R2013b)Revised for Version 8.3 (R2014a)Revised for Version 8.4 (R2014b)Revised for Version 8.5 (R2015a)Revised for Version 8.6 (R2015b)Revised for Version 9.0 (R2016a)Revised for Version 9.1 (R2016b)Revised for Version 9.2 (R2017a)Revised for Version 9.3 (R2017b)

Contents1Quick StartMATLAB Product Description . . . . . . . . . . . . . . . . . . . . . . . . . .Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-21-2Desktop Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-4Matrices and Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-7Array Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-12Workspace Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-15Text and Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-17Calling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-192-D and 3-D Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Line Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-D Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-211-211-261-27Programming and Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . .Sample Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Loops and Conditional Statements . . . . . . . . . . . . . . . . . . . .Script Locations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-291-291-301-32Help and Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-33v

2viContentsLanguage FundamentalsMatrices and Magic Squares . . . . . . . . . . . . . . . . . . . . . . . . . . .About Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Entering Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .sum, transpose, and diag . . . . . . . . . . . . . . . . . . . . . . . . . . . .The magic Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Generating Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-22-22-42-52-72-8Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Matrix Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Array Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Examples of Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . .2-92-92-102-112-112-132-14Entering Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .The format Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Suppressing Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Entering Long Statements . . . . . . . . . . . . . . . . . . . . . . . . . .Command Line Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-162-162-172-172-18Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Subscripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .The Colon Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Deleting Rows and Columns . . . . . . . . . . . . . . . . . . . . . . . . .Scalar Expansion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Logical Subscripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .The find Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-192-192-202-212-222-232-232-24Types of Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . .Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Characters and Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-262-262-282-302-33

34MathematicsLinear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Matrices in the MATLAB Environment . . . . . . . . . . . . . . . . .Systems of Linear Equations . . . . . . . . . . . . . . . . . . . . . . . .Inverses and Determinants . . . . . . . . . . . . . . . . . . . . . . . . . .Factorizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Powers and Exponentials . . . . . . . . . . . . . . . . . . . . . . . . . . .Eigenvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Singular Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-23-23-103-223-263-333-373-40Operations on Nonlinear Functions . . . . . . . . . . . . . . . . . . . .Function Handles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Function Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-443-443-44Multivariate Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-47Data Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Preprocessing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Summarizing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Visualizing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Modeling Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-483-483-483-543-583-70GraphicsBasic Plotting Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Creating a Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Plotting Multiple Data Sets in One Graph . . . . . . . . . . . . . . .Specifying Line Styles and Colors . . . . . . . . . . . . . . . . . . . . . .Plotting Lines and Markers . . . . . . . . . . . . . . . . . . . . . . . . . .Graphing Imaginary and Complex Data . . . . . . . . . . . . . . . . .Adding Plots to an Existing Graph . . . . . . . . . . . . . . . . . . . .Figure Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Displaying Multiple Plots in One Figure . . . . . . . . . . . . . . . .Controlling the Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Adding Axis Labels and Titles . . . . . . . . . . . . . . . . . . . . . . . .4-24-24-44-64-74-94-104-124-124-134-15vii

5viiiContentsSaving Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Saving Workspace Data . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-164-17Creating Mesh and Surface Plots . . . . . . . . . . . . . . . . . . . . . .About Mesh and Surface Plots . . . . . . . . . . . . . . . . . . . . . . .Visualizing Functions of Two Variables . . . . . . . . . . . . . . . .4-194-194-19Display Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Image Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Reading and Writing Images . . . . . . . . . . . . . . . . . . . . . . . .4-254-254-27Printing Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Overview of Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Printing from the File Menu . . . . . . . . . . . . . . . . . . . . . . . . .Exporting the Figure to a Graphics File . . . . . . . . . . . . . . . .Using the Print Command . . . . . . . . . . . . . . . . . . . . . . . . . .4-284-284-284-294-29Working with Graphics Objects . . . . . . . . . . . . . . . . . . . . . . . .Graphics Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Setting Object Properties . . . . . . . . . . . . . . . . . . . . . . . . . . .Functions for Working with Objects . . . . . . . . . . . . . . . . . . .Passing Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Finding the Handles of Existing Objects . . . . . . . . . . . . . . . .4-304-304-334-354-364-37ProgrammingControl Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Conditional Control — if, else, switch . . . . . . . . . . . . . . . . . . .Loop Control — for, while, continue, break . . . . . . . . . . . . . . .Program Termination — return . . . . . . . . . . . . . . . . . . . . . . .Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Preallocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-25-25-55-75-75-8Scripts and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Types of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-95-95-105-115-135-15

Command vs. Function Syntax . . . . . . . . . . . . . . . . . . . . . . .5-15ix

1Quick Start “MATLAB Product Description” on page 1-2 “Desktop Basics” on page 1-4 “Matrices and Arrays” on page 1-7 “Array Indexing” on page 1-12 “Workspace Variables” on page 1-15 “Text and Characters” on page 1-17 “Calling Functions” on page 1-19 “2-D and 3-D Plots” on page 1-21 “Programming and Scripts” on page 1-29 “Help and Documentation” on page 1-33

1Quick StartMATLAB Product DescriptionThe Language of Technical ComputingMillions of engineers and scientists worldwide use MATLAB to analyze and design thesystems and products transforming our world. MATLAB is in automobile active safetysystems, interplanetary spacecraft, health monitoring devices, smart power grids, andLTE cellular networks. It is used for machine learning, signal processing, imageprocessing, computer vision, communications, computational finance, control design,robotics, and much more.Math. Graphics. Programming.The MATLAB platform is optimized for solving engineering and scientific problems. Thematrix-based MATLAB language is the world’s most natural way to expresscomputational mathematics. Built-in graphics make it easy to visualize and gain insightsfrom data. A vast library of pre-built toolboxes lets you get started right away withalgorithms essential to your domain. The desktop environment invites experimentation,exploration, and discovery. These MATLAB tools and capabilities are all rigorouslytested and designed to work together.Scale. Integrate. Deploy.MATLAB helps you take your ideas beyond the desktop. You can run your analyses onlarger data sets, and scale up to clusters and clouds. MATLAB code can be integratedwith other languages, enabling you to deploy algorithms and applications within web,enterprise, and production systems.Key Features High-level language for scientific and engineering computing Desktop environment tuned for iterative exploration, design, and problem-solving Graphics for visualizing data and tools for creating custom plots Apps for curve fitting, data classification, signal analysis, control system tuning, andmany other tasks Add-on toolboxes for a wide range of engineering and scientific applications Tools for building applications with custom user interfaces Interfaces to C/C , Java , .NET, Python, SQL, Hadoop, and Microsoft Excel 1-2

MATLAB Product Description Royalty-free deployment options for sharing MATLAB programs with end users1-3

1Quick StartDesktop BasicsWhen you start MATLAB, the desktop appears in its default layout.The desktop includes these panels: Current Folder — Access your files. Command Window — Enter commands at the command line, indicated by theprompt ( ). Workspace — Explore data that you create or import from files.As you work in MATLAB, you issue commands that create variables and call functions.For example, create a variable named a by typing this statement at the command line:a 11-4

Desktop BasicsMATLAB adds variable a to the workspace and displays the result in the CommandWindow.a 1Create a few more variables.b 2b 2c a bc 3d cos(a)d 0.5403When you do not specify an output variable, MATLAB uses the variable ans, short foranswer, to store the results of your calculation.sin(a)ans 0.8415If you end a statement with a semicolon, MATLAB performs the computation, butsuppresses the display of output in the Command Window.e a*b;You can recall previous commands by pressing the up- and down-arrow keys, and .Press the arrow keys either at an empty command line or after you type the first fewcharacters of a command. For example, to recall the command b 2, type b, and thenpress the up-arrow key.1-5

1Quick StartSee Also“Matrices and Arrays” on page 1-71-6

Matrices and ArraysMatrices and ArraysMATLAB is an abbreviation for "matrix laboratory." While other programming languagesmostly work with numbers one at a time, MATLAB is designed to operate primarily onwhole matrices and arrays.All MATLAB variables are multidimensional arrays, no matter what type of data. Amatrix is a two-dimensional array often used for linear algebra.Array CreationTo create an array with four elements in a single row, separate the elements with eithera comma (,) or a space.a [1 2 3 4]a 1234This type of array is a row vector.To create a matrix that has multiple rows, separate the rows with semicolons.a [1 2 3; 4 5 6; 7 8 10]a 1472583610Another way to create a matrix is to use a function, such as ones, zeros, or rand. Forexample, create a 5-by-1 column vector of zeros.z zeros(5,1)z 0001-7

1Quick Start00Matrix and Array OperationsMATLAB allows you to process all of the values in a matrix using a single arithmeticoperator or function.a 10ans 111417121518131620sin(a)ans 4-0.5440To transpose a matrix, use a single quote ('):a'ans 1234567810You can perform standard matrix multiplication, which computes the inner productsbetween rows and columns, using the * operator. For example, confirm that a matrixtimes its inverse returns the identity matrix:p a*inv(a)p 1-8

Matrices and Arrays1.00000001.00000-0.000001.0000Notice that p is not a matrix of integer values. MATLAB stores numbers as floating-pointvalues, and arithmetic operations are sensitive to small differences between the actualvalue and its floating-point representation. You can display more decimal digits usingthe format command:format longp a*inv(a)p 00000000.999999999999998Reset the display to the shorter format usingformat shortformat affects only the display of numbers, not the way MATLAB computes or savesthem.To perform element-wise multiplication rather than matrix multiplication, use the .*operator:p a.*ap 1164942564936100The matrix operators for multiplication, division, and power each have a correspondingarray operator that operates element-wise. For example, raise each element of a to thethird power:a. 3ans 1-9

1Quick ion is the process of joining arrays to make larger ones. In fact, you made yourfirst array by concatenating its individual elements. The pair of square brackets [] is theconcatenation operator.A [a,a]A 14725836101472583610Concatenating arrays next to one another using commas is called horizontalconcatenation. Each array must have the same number of rows. Similarly, when thearrays have the same number of columns, you can concatenate vertically usingsemicolons.A [a; a]A 14714725825836103610Complex NumbersComplex numbers have both real and imaginary parts, where the imaginary unit is thesquare root of -1.sqrt(-1)1-10

See Alsoans 0.0000 1.0000iTo represent the imaginary part of complex numbers, use either i or j .c [3 4i, 4 3j; -i, 10j]c 3.0000 4.0000i0.0000 - 1.0000i4.0000 3.0000i0.0000 10.0000iSee Also“Array Indexing” on page 1-121-11

1Quick StartArray IndexingEvery variable in MATLAB is an array that can hold many numbers. When you want toaccess selected elements of an array, use indexing.For example, consider the 4-by-4 magic square A:A magic(4)A 16594211714310615138121There are two ways to refer to a particular element in an array. The most common way isto specify row and column subscripts, such asA(4,2)ans 14Less common, but sometimes useful, is to use a single subscript that traverses down eachcolumn in order:A(8)ans 14Using a single subscript to refer to a particular element in an array is called linearindexing.If you try to refer to elements outside an array on the right side of an assignmentstatement, MATLAB throws an error.1-12

Array Indexingtest A(4,5)Index exceeds matrix dimensions.However, on the left side of an assignment statement, you can specify elements outsidethe current dimensions. The size of the array increases to accommodate the newcomers.A(4,5) 17A 1659421171431061513812100017To refer to multiple elements of an array, use the colon operator, which allows you tospecify a range of the form start:end. For example, list the elements in the first threerows and the second column of A:A(1:3,2)ans 2117The colon alone, without start or end values, specifies all of the elements in thatdimension. For example, select all the columns in the third row of A:A(3,:)ans 976120The colon operator also allows you to create an equally spaced vector of values using themore general form start:step:end.1-13

1Quick StartB 0:10:100B 0102030405060708090100If you omit the middle step, as in start:end, MATLAB uses the default step value of 1.See Also“Workspace Variables” on page 1-151-14

Workspace VariablesWorkspace VariablesThe workspace contains variables that you create within or import into MATLAB fromdata files or other programs. For example, these statements create variables A and B inthe workspace.A magic(4);B rand(3,5,2);You can view the contents of the workspace using tesdoubledoubleThe variables also appear in the Workspace pane on the desktop.Workspace variables do not persist after you exit MATLAB. Save your data for later usewith the save command,save myfile.matSaving preserves the workspace in your current working folder in a compressed file witha .mat extension, called a MAT-file.To clear all the variables from the workspace, use the clear command.Restore data from a MAT-file into the workspace using load.load myfile.mat1-15

1Quick StartSee Also“Text and Characters” on page 1-171-16

Text and CharactersText and CharactersWhen you are working with text, enclose sequences of characters in single quotes. Youcan assign text to a variable.myText 'Hello, world';If the text includes a single quote, use two single quotes within the definition.otherText 'You''re right'otherText 'You're right'myText and otherText are arrays, like all MATLAB variables. Their class or datatype is char, which is short for character.whos You can concatenate character arrays with square brackets, just as you concatenatenumeric arrays.longText [myText,' - ',otherText]longText 'Hello, world - You're right'To convert numeric values to characters, use functions, such as num2str or int2str.f 71;c (f-32)/1.8;tempText ['Temperature is ',num2str(c),'C']tempText 'Temperature is 21.6667C'1-17

1Quick StartSee Also“Calling Functions” on page 1-191-18

Calling FunctionsCalling FunctionsMATLAB provides a large number of functions that perform computational tasks.Functions are equivalent to subroutines or methods in other programming languages.To call a function, such as max, enclose its input arguments in parentheses:A [1 3 5];max(A)ans 5If there are multiple input arguments, separate them with commas:B [10 6 4];max(A,B)ans 1065Return output from a function by assigning it to a variable:maxA max(A)maxA 5When there are multiple output arguments, enclose them in square brackets:[maxA,location] max(A)maxA 5location 3Enclose any character inputs in single quotes:disp('hello world')hello worldTo call a function that does not require any inputs and does not return any outputs, typeonly the function name:clc1-19

1Quick StartThe clc function clears the Command Window.See Also“2-D and 3-D Plots” on page 1-211-20

2-D and 3-D Plots2-D and 3-D PlotsIn this section.“Line Plots” on page 1-21“3-D Plots” on page 1-26“Subplots” on page 1-27Line PlotsTo create two-dimensional line plots, use the plot function. For example, plot the valueof the sine function from 0 to:x 0:pi/100:2*pi;y sin(x);plot(x,y)1-21

1Quick StartYou can label the axes and add a title.xlabel('x')ylabel('sin(x)')title('Plot of the Sine Function')1-22

2-D and 3-D PlotsBy adding a third input argument to the plot function, you can plot the same variablesusing a red dashed line.plot(x,y,'r--')1-23

1Quick StartThe 'r--' string is a line specification. Each specification can include characters for theline color, style, and marker. A marker is a symbol that appears at each plotted datapoint, such as a , o, or *. For example, 'g:*' requests a dotted green line with *markers.Notice that the titles and labels that you defined for the first plot are no longer in thecurrent figure window. By default, MATLAB clears the figure each time you call aplotting function, resetting the axes and other elements to prepare the new plot.To add plots to an existing figure, use hold.x 0:pi/100:2*pi;y sin(x);1-24

2-D and 3-D Plotsplot(x,y)hold ony2 cos(x);plot(x,y2,':')legend('sin','cos')Until you use hold off or close the window, all plots appear in the current figurewindow.1-25

1Quick Start3-D PlotsThree-dimensional plots typically display a surface defined by a function in twovariables, z f(x,y) .To evaluate z, first create a set of (x,y) points over the domain of the function usingmeshgrid.[X,Y] meshgrid(-2:.2:2);Z X .* exp(-X. 2 - Y. 2);Then, create a surface plot.surf(X,Y,Z)1-26

2-D and 3-D PlotsBoth the surf function and its companion mesh display surfaces in three dimensions.surf displays both the connecting lines and the faces of the surface in color. meshproduces wireframe surfaces that color only the lines connecting the defining points.SubplotsYou can display multiple plots in different subregions of the same window using thesubplot function.The first two inputs to subplot indicate the number of plots in each row and column.The third input specifies which plot is active. For example, create four plots in a 2-by-2grid within a figure window.t 0:pi/10:2*pi;[X,Y,Z] cylinder(4*cos(t));subplot(2,2,1); mesh(X); title('X');subplot(2,2,2); mesh(Y); title('Y');subplot(2,2,3); mesh(Z); title('Z');subplot(2,2,4); mesh(X,Y,Z); title('X,Y,Z');1-27

1Quick StartSee Also“Programming and Scripts” on page 1-291-28

Programming and ScriptsProgramming and ScriptsIn this section.“Sample Script” on page 1-29“Loops and Conditional Statements” on page 1-30“Script Locations” on page 1-32The simplest type of MATLAB program is called a script. A script is a file with a .mextension that contains multiple sequential lines of MATLAB commands and functioncalls. You can run a script by typing its name at the command line.Sample ScriptTo create a script, use the edit command,edit plotrandThis opens a blank file named plotrand.m. Enter some code that plots a vector ofrandom data:n 50;r rand(n,1);plot(r)Next, add code that draws a horizontal line on the plot at the mean:m mean(r);hold onplot([0,n],[m,m])hold offtitle('Mean of Random Uniform Data')Whenever you write code, it is a good practice to add comments that describe the code.Comments allow others to understand your code, and can refresh your memory when youreturn to it later. Add comments using the percent (%) symbol.% Generate random data from a uniform distribution% and calculate the mean. Plot the data and the mean.n 50;r rand(n,1);% 50 data points1-29

1Quick Startplot(r)% Draw a line from (0,m) to (n,m)m mean(r);hold onplot([0,n],[m,m])hold offtitle('Mean of Random Uniform Data')Save the file in the current folder. To run the script, type its name at the command line:plotrandYou can also run scripts from the Editor by pressing the Run button,.Loops and Conditional StatementsWithin a script, you can loop over sections of code and conditionally execute sectionsusing the keywords for, while, if, and switch.For example, create a script named calcmean.m that uses a for loop to calculate themean of five random samples and the overall mean.nsamples 5;npoints 50;for k 1:nsamplescurrentData rand(npoints,1);sampleMean(k) mean(currentData);endoverallMean mean(sampleMean)Now, modify the for loop so that you can view the results at each iteration. Display textin the Command Window that includes the current iteration number, and remove thesemicolon from the assignment to sampleMean.for k 1:nsamplesiterationString ['Iteration #',int2str(k)];disp(iterationString)currentData rand(npoints,1);sampleMean(k) mean(currentData)endoverallMean mean(sampleMean)1-30 p

July 2002 Online only Revised for MATLAB 6.5 (Release 13) August 2002 Fifth printing Revised for MATLAB 6.5 June 2004 Sixth printing Revised for MATLAB 7.0 (Release 14) October 2004 Online only Revised for MATLAB 7.0.1 (Release 14SP1) March 2005 Online only Revised for MATLAB 7.0.4 (Release 14SP2)

Related Documents:

Latin Primer 1: Teacher's Edition Latin Primer 1: Flashcard Set Latin Primer 1: Audio Guide CD Latin Primer: Book 2, Martha Wilson (coming soon) Latin Primer 2: Student Edition Latin Primer 2: Teacher's Edition Latin Primer 2: Flashcard Set Latin Primer 2: Audio Guide CD Latin Primer: Book 3, Martha Wilson (coming soon) Latin Primer 3 .

MATLAB tutorial . School of Engineering . Brown University . To prepare for HW1, do sections 1-11.6 – you can do the rest later as needed . 1. What is MATLAB 2. Starting MATLAB 3. Basic MATLAB windows 4. Using the MATLAB command window 5. MATLAB help 6. MATLAB ‘Live Scripts’ (for algebra, plotting, calculus, and solving differential .

19 MATLAB Excel Add-in Hadoop MATLAB Compiler Standalone Application MATLAB deployment targets MATLAB Compiler enables sharing MATLAB programs without integration programming MATLAB Compiler SDK provides implementation and platform flexibility for software developers MATLAB Production Server provides the most efficient development path for secure and scalable web and enterprise applications

MATLAB tutorial . School of Engineering . Brown University . To prepare for HW1, do sections 1-11.6 – you can do the rest later as needed . 1. What is MATLAB 2. Starting MATLAB 3. Basic MATLAB windows 4. Using the MATLAB command window 5. MATLAB help 6. MATLAB ‘Live Scripts’ (for

3. MATLAB script files 4. MATLAB arrays 5. MATLAB two‐dimensional and three‐dimensional plots 6. MATLAB used‐defined functions I 7. MATLAB relational operators, conditional statements, and selection structures I 8. MATLAB relational operators, conditional statements, and selection structures II 9. MATLAB loops 10. Summary

foundation of basic MATLAB applications in engineering problem solving, the book provides opportunities to explore advanced topics in application of MATLAB as a tool. An introduction to MATLAB basics is presented in Chapter 1. Chapter 1 also presents MATLAB commands. MATLAB is considered as the software of choice. MATLAB can be used .

I. Introduction to Programming Using MATLAB Chapter 1: Introduction to MATLAB 1.1 Getting into MATLAB 1.2 The MATLAB Desktop Environment 1.3 Variables and Assignment Statements 1.4 Expressions 1.5 Characters and Encoding 1.6 Vectors and Matrices Chapter 2: Introduction to MATLAB Programming 2.1 Algorithms 2.2 MATLAB Scripts 2.3 Input and Output

Compiler MATLAB Production Server Standalone Application MATLAB Compiler SDK Apps Files Custom Toolbox Python With MATLAB Users With People Who Do Not Have MATLAB.lib/.dll .exe . Pricing Risk Analytics Portfolio Optimization MATLAB Production Server MATLAB CompilerSDK Web Application