ebook img

Matlab. A Practical Introduction to Programming and Problem Solving PDF

541 Pages·2014·9.159 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Matlab. A Practical Introduction to Programming and Problem Solving

CHAPTER 1 Introduction to MATLAB KEY TERMS CONTENTS prompt characters logarithm 1.1 Getting into MATLAB........4 programs strings commonlogarithm scriptfiles casting natural logarithm 1.2 The MATLAB Desktop Envi- toolstrip typecasting constants ronment variable saturationarithmetic randomnumbers ........................5 assignment statement default seed 1.3 Variables and assignment operator continuationoperator pseudorandom Assignment user ellipsis openinterval Statements....6 initializing unary global stream 1.4 Numerical incrementing operand character encoding Expressions ......................12 decrementing binary character set identifier names scientific notation relational expression 1.5 Charactersand Encoding.....21 reservedwords exponentialnotation Boolean expression keywords precedence logical expression 1.6 Relational mnemonic associativity relational operators Expressions ......................23 types nestedparentheses logical operators classes innerparentheses scalars double precision help topics short-circuit operators floating point call afunction truth table unsigned arguments commutative range returningvalues (cid:1) MATLAB isaverypowerfulsoftwarepackagethathasmanybuilt-intoolsfor solvingproblemsanddevelopinggraphicalillustrations.Thesimplestmethod forusing the MATLAB product is interactively;anexpression isentered bythe user and MATLAB responds immediately with a result. It is also possible to 3 MATLAB(cid:1).http://dx.doi.org/10.1016/B978-0-12-405876-7.00001-8 Copyright(cid:3)2013ElsevierInc.Allrightsreserved. 4 CHAPTER 1: Introduction to MATLAB write scripts and programs in MATLAB, which are essentially groups of commands that are executed sequentially. This chapter will focus on the basics, including many operators and built-in functions that can be used in interactive expressions. 1.1 GETTING INTO MATLAB MATLAB is a mathematical and graphical software package with numerical, graphical, and programming capabilities. It has built-in functions to perform many operations, and there are toolboxes that can be added to augment these functions (e.g., for signal processing). There are versions available for different hardware platforms, in both professional and student editions. WhentheMATLABsoftwareisstarted,awindowopensinwhichthemainpart is the Command Window (see Figure 1.1). In the Command Window, you should see: >> FIGURE 1.1 MATLABcommandwindow 1.2 The MATLAB Desktop Environment 5 The >> is called the prompt. In the Student edition, the prompt instead is: EDU>> IntheCommandWindow,MATLABcanbeusedinteractively.Attheprompt, any MATLAB command or expression can be entered, and MATLAB will respond immediately with the result. ItisalsopossibletowriteprogramsinMATLABthatarecontainedinscriptfiles or M-files. Programs will be introduced in Chapter 3. The following commands can serve as an introduction to MATLAB and allow you to get help: n demo will bring up MATLAB examples in the Help Browser, which has examples of some of the features of MATLAB n help will explain any function; help help will explain how help works n lookfor searches through the help for a specific word or phrase (note: this can take a long time) n doc will bring up a documentation page in the Help Browser. To exit from MATLAB, either type quit or exit at the prompt, or click on MATLAB, then Quit MATLAB from the menu. 1.2 THE MATLAB DESKTOP ENVIRONMENT In addition to the Command Window, there are several other windows that can be opened and may be opened by default. What is described here is the defaultlayoutforthesewindowsinVersionR2012b,althoughthereareother possible configurations. Different versions of MATLAB may show other configurationsbydefault,andthelayoutcanalwaysbecustomized.Therefore, the main features will be described briefly here. To the left of the Command Window is the Current Folder Window. The folderthatissetastheCurrentFolderiswherefileswillbesaved.Thiswindow shows the files that are stored in the Current Folder. These can be grouped in manyways,forexample,bytype,andsorted,forexample,byname.Ifafileis selected, information about that file is shown on the bottom. TotherightoftheCommandWindowaretheWorkspaceWindowontopand the Command History Window on the bottom. The Command History Window shows commands that have been entered, not just in the current session (in the current Command Window), but previously as well. The Workspace Window will be described in the next section. This default configuration can be altered by clicking the down arrow at the top right corner of each window. This will show a menu of options 6 CHAPTER 1: Introduction to MATLAB (different for each window), including, for example, closing that particular window and undocking that window. Once undocked, bringing up the menu and then clicking on the curled arrow pointing to the lower right will dock the window again. To make any of these windows the active window, click the mouse in it. By default, the active window is the Command Window. Beginning with Version 2012b, the look and feel of the Desktop Environ- ment has been completely changed. Instead of menus and toolbars, the Desktop now has a toolstrip. By default, three tabs are shown (“HOME”, “PLOTS”, and “APPS”), although others, including “SHORTCUTS”, can be added. Underthe“HOME”tabtherearemanyusefulfeatures,whicharedividedinto functional sectionsd“FILE”, “VARIABLE”, “CODE”, “ENVIRONMENT”, and “RESOURCES” (these labels can be seen on the very bottom of the gray toolstriparea).Forexample,under“ENVIRONMENT”,hittingthedownarrow under Layout allows for customization of the windows within the Desktop Environment. Other toolstrip features will be introduced in later chapters when the relevant material is explained. 1.3 VARIABLES AND ASSIGNMENT STATEMENTS TostoreavalueinaMATLABsession,orinaprogram,avariable isused.The Workspace Window shows variables that have been created and their values. Oneeasywaytocreateavariableistouseanassignmentstatement.Theformat of an assignment statement is variablename = expression The variable is always on the left, followed by the ¼ symbol, which is the assignment operator (unlike in mathematics, the single equal sign does not mean equality), followed by an expression. The expression is evaluated and thenthatvalueisstoredinthevariable.Hereisanexampleandhowitwould appear in the Command Window: >> mynum = 6 mynum = 6 >> Here, the user (the person working in MATLAB) typed “mynum ¼ 6” at the prompt, and MATLAB stored the integer 6 in the variable called mynum, and then displayed the result followed by the prompt again. As the equal sign is theassignmentoperator,anddoesnotmeanequality,thestatementshouldbe read as “mynum gets the value of 6” (not “mynum equals 6”). 1.3 Variables and Assignment Statements 7 Notethatthevariablenamemustalwaysbeontheleft,andtheexpressionon the right. An error will occur if these are reversed. >> 6 = mynum 6 = mynum j Error: The expression to the left of the equals sign is not a valid target for an assignment. >> Putting a semicolon at the end of a statement suppresses the output. For example, >> res = 9 e 2; >> Thiswouldassigntheresultoftheexpressionontherightside,thevalue7,to the variable res; it just does not show that result. Instead, another prompt appears immediately. However, at this point in the Workspace Window both the variables mynum and res and their values can be seen. Note Intheremainderofthe The spaces in a statement or expression do not affect the result, but make it text,thepromptthat easier to read. The following statement, which has no spaces, would accom- appearsaftertheresult plish exactly the same result as the previous statement: willnotbeshown. >> res = 9-2; MATLAB uses a default variable named ans if an expression is typed at the prompt and it is not assigned to a variable. For example, the result of the expression 6 þ 3 is stored in the variable ans: >> 6 þ 3 ans = 9 This default variable is reused any time only an expression is typed at the prompt. Ashortcutforretypingcommandsistohittheuparrow[,whichwillgoback tothepreviouslytypedcommand(s).Forexample,ifyoudecidedtoassignthe result of the expression 6 þ 3 to a variable named result instead of using the default variable ans, you could hit the up arrow and then the left arrow to modify the command rather than retyping the entire statement: >> result = 6 þ 3 result = 9 Thisisveryuseful,especiallyifalongexpressionisenteredanditcontainsan error, and it is desired to go back to correct it. 8 CHAPTER 1: Introduction to MATLAB Tochangeavariable,anotherassignmentstatementcanbeused,whichassigns the value of a different expression to it. Consider, for example, the following sequence of statements: >> mynum = 3 mynum = 3 >> mynum = 4 þ 2 mynum = 6 >> mynum = mynum þ 1 mynum = 7 In the first assignment statement, the value 3 is assigned to the variable mynum.Inthenextassignmentstatement,mynumischangedtohavethevalue of the expression 4 þ 2, or 6. In the third assignment statement, mynum is changed again, to the result of the expression mynum þ 1. Since, at that time, mynum had the value 6, the value of the expression was 6 þ 1, or 7. Atthatpoint,iftheexpressionmynumþ3isentered,thedefaultvariableansis used as the result of this expression is not assigned to a variable. Thus, the valueofansbecomes10,butmynumisunchanged(itisstill7).Notethatjust typing the name of a variable will display its value (of course, the value can also be seen in the Workspace Window). >> mynum þ 3 ans = 10 >> mynum mynum = 7 1.3.1 Initializing, Incrementing, and Decrementing Frequently,valuesofvariableschange,asshownpreviously.Puttingthefirstor initial value in a variable is called initializing the variable. Adding to a variable is called incrementing. For example, the statement mynum = mynum þ 1 increments the variable mynum by 1. QUICK QUESTION! How can1 be subtracted from the valueof a variable called Thisiscalleddecrementingthevariable. num? Answer num = num e 1; 1.3 Variables and Assignment Statements 9 1.3.2 Variable names Variablenamesareexamplesofidentifiernames.Wewillseeotherexamplesof identifier names, such as function names, in future chapters. The rules for identifier names are as follows. n Thenamemustbeginwithaletterofthealphabet.Afterthat,thenamecan contain letters, digits, and the underscore character (e.g., value_1), but it cannot have a space. n There is a limit to the length of the name; the built-in function namelengthmax tells what this maximum length is (any extra characters are truncated). n MATLAB is case-sensitive, which means that there is a difference between upper- and lowercase letters. So, variables called mynum, MYNUM, and Mynumarealldifferent(althoughthiswouldbeconfusingandshouldnot be done). n Althoughunderscorecharactersarevalidinaname,theirusecancause problemswithsomeprogramsthatinteractwithMATLAB,sosome programmersusemixedcaseinstead(e.g.,partWeightsinsteadofpart_weights). n There are certain words called reserved words, or keywords, that cannot be used as variable names. n Namesofbuilt-infunctions(describedinthenextsection)can,butshould not, be used as variable names. Additionally,variablenamesshouldalwaysbemnemonic,whichmeansthat they should make some sense. For example, if the variable is storing the radius of a circle, a name such as radius would make sense; x probably wouldn’t. The following commands relate to variables: n who shows variables that have been defined in this Command Window (this just shows the names of the variables) n whos shows variables that have been defined in this Command Window (this shows more information on the variables, similar to what is in the Workspace Window) n clear clears out all variables so they no longer exist n clear variablename clears out a particular variable n clear variablename1 variablename2 . clears out a list of variables (note: separate the names with spaces). If nothing appears when who or whos is entered, that means there aren’t any variables!Forexample,inthebeginningofaMATLABsession,variablescould be created and then selectively cleared (remember that the semicolon suppresses output). 10 CHAPTER 1: Introduction to MATLAB >> who >> mynum = 3; >> mynum þ 5; >> who Your variables are: ans mynum >> clear mynum >> who Your variables are: ans These changes can also be seen in the Workspace Window. 1.3.3 Types Every variable has a type associated with it. MATLAB supports many types, whicharecalledclasses.(Essentially,aclassisacombinationofatypeandthe operationsthatcanbeperformedonvaluesofthattype,but,forsimplicity,we will use these terms interchangeably for now.) For example, there are types to store different kinds of numbers. For float or real numbers, or, in other words, numbers with a decimal place (e.g., 5.3), there are two basic types: single and double. The name of the type double is short for double precision; it stores larger numbers than the single type. MATLAB uses a floating point representation for these numbers. There are many integer types, such as int8, int16, int32, and int64. The numbersinthenamesrepresentthenumberofbitsusedtostorevaluesofthat type. For example, the type int8 uses eight bits altogether to store the integer anditssign.Asonebitisusedforthesign,thismeansthatsevenbitsareused tostoreactualnumbers(0sor1s).Therearealsounsignedintegertypesuint8, uint16, uint32, and uint64. For these types, the sign is not stored, meaning that the integer can only be positive (or 0). Therangeofatype,whichindicatesthesmallestandlargestnumbersthatcan bestoredinthetype,canbecalculated.Forexample,thetypeuint8stores2^8 or256integers,rangingfrom0to255.Therangeofvaluesthatcanbestored inint8,however,isfrome128toþ127.Therangecanbefoundforanytype bypassing thename ofthetype asastring(whichmeansinsinglequotes)to the functions intmin and intmax. For example, >> intmin('int8') ans = -128 >> intmax('int8') ans = 127 Thelargerthenumberinthetypename,thelargerthenumberthatcanbestored init.Wewill,forthemostpart,usethetypeint32whenanintegertypeisrequired. 1.3 Variables and Assignment Statements 11 Thetypecharisusedtostoreeithersinglecharacters(e.g.,‘x’)orstrings,which aresequencesofcharacters(e.g.,‘cat’).Bothcharactersandstringsareenclosed in single quotes. The type logical is used to store true/false values. Variables that have been created in the Command Window can be seen in the Workspace Window. In that window, for every variable, the variable name, value, and class (which is, essentially, its type) can be seen. Other attributes of variables can also be seen in the Workspace Window. Which attributes are visible by default depends on the version of MATLAB. However, when the Workspace Window is chosen, clicking on the down arrow allows the user to choose which attributes will be displayed by modifying Choose Columns. By default, numbers are stored as the type double in MATLAB. There are, however, many functions that convert values from one type to another. The names of these functions are the same as the names of the types shown in this section. These names can be used as functions to convert a value to that type. This is called casting the value to a different type, or type casting. For example,toconvertavaluefromthetypedouble,whichisthedefault,tothe type int32, the function int32 would be used. Entering the assignment statement >> val = 6 þ 3; wouldresultinthenumber9beingstoredinthevariableval,withthedefault type of double, which can be seen in the Workspace Window. Subsequently, the assignment statement >> val = int32(val); wouldchangethetypeofthevariabletoint32,butwouldnotchangeitsvalue. Here is another example using two different variables. >> num = 6 þ 3; >> numi = int32(num); >> whos Name Size Bytes Class Attributes num 1x1 8 double numi 1x1 4 int32 Note that whos shows the type (class) of the variables, as well as the number of bytes used to store the value of a variable. One byte is equivalent to eight bits, so the type int32 uses four bytes. The function class can also be used to see the type of a variable: >> class(num) ans = double 12 CHAPTER 1: Introduction to MATLAB One reason for using an integer type for a variable is to save space in memory. QUICK QUESTION! Whatwouldhappenifyougobeyondtherangeforaparticular lowest value in the range, its value would be e128. This is type? For example, the largest integer that can be stored in anexampleofwhatiscalledsaturationarithmetic. int8 is 127, so what would happen if we type cast a larger >> int8(200) integertothetypeint8? ans = >> int8(200) 127 >> int8(-130) Answer ans = Thevaluewouldbethelargestintherange,inthiscase127.If, -128 instead, we use a negative number that is smaller than the PRACTICE 1.1 n Calculatetherangeofintegersthatcanbestoredinthetypesint16anduint16.Useintmin andintmaxtoverifyyourresults. n EnteranassignmentstatementandviewthetypeofthevariableintheWorkspaceWindow. Then,changeitstypeandviewitagain.Viewitalsousingwhos. 1.4 NUMERICAL EXPRESSIONS Expressions can be created using values, variables that have already been created,operators,built-infunctions,andparentheses.Fornumbers,thesecan includeoperators,suchasmultiplication,andfunctions,suchastrigonometric functions. An example of such an expression is: >> 2 * sin(1.4) ans = 1.9709 1.4.1 The Format Function and Ellipsis The default in MATLAB is to display numbers that have decimal points with four decimal places, as shown in the previousexample. (The default means if youdonotspecifyotherwise,thisiswhatyouget.)Theformatcommandcan be used to specify the output format of expressions. There are many options, including making the format short (the default) or long. For example, changing the format to long will result in 15 decimal places. This will remain in effect until the format is changed back to short, as demonstrated in the following:

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.