loading

Logout succeed

Logout succeed. See you again!

ebook img

Matlab by Example. Programming Basics PDF

pages353 Pages
release year2013
file size13.283 MB
languageEnglish

Preview Matlab by Example. Programming Basics

1 Matlab Integrated Development Environment ChapterOutline Lesson1.1 BasicsoftheMatlabIntegratedDevelopmentEnvironment 1 Lesson1.2 MatlabScriptFiles 8 Lesson1.3 MatlabEditor—CellMode 17 AnswerstoSelectedExercises 20 Lesson 1.1 Basics of the Matlab Integrated Development Environment Objectives (cid:1) TofamiliarizebeginnersinMatlabwithitsprogrammingenvironment. (cid:1) To learn how to use Matlab to execute simple commands, create variables, and displaytheirvalues. Topics 1.1.1 MatlabIntegratedDevelopmentEnvironment 1.1.2 CreatingScalarVariables 1.1.3 CreatingVectorVariables 1.1.4 CreatingArrayVariables 1.1.1 Matlab Integrated Development Environment Matlab version 7.12 (R2011a) is used here to explain the integrated development environment (IDE). Even though this specific version of Matlab has been used here, other Matlab versions can still be used to follow the discussions presented in thisbookifyoudonothavethisexactversion. First launch Matlab. When MATLAB opens you should see four windows: the Command Window, the Command History, the Workspace, and the Current MatlabbyExample.DOI:http://dx.doi.org/10.1016/B978-0-12-405212-3.00001-3 ©2013ElsevierInc.Allrightsreserved. 2 MatlabbyExample Folder. If you do not see these windows, you can direct Matlab to display them by going to the Menu!Desktop and then click the window you would like to dis- play,sothatithas atickünext toit. Forexample, ifyouwouldliketodisplaythe Command Window, go to Menu!Desktop and then click the Command Window. Menu Command Window title bar In addition to your ability to display the required windows, you can arrange them in any way you prefer. This can be achieved by clicking the title bar of any window, dragging it, and placing it in the required location within the Matlab main window. ‡Exercise11 Display the four windows and arrange them as shown. Remember, the four windows are the Command Window, the Command History, the Workspace, and the Current Folder. ‡Thesuperscriptaftertheexercisenumberdenotestheexercisedifficultylevel:1beingbasic,2inter- mediate,and3beinganadvancedtask. MatlabIntegratedDevelopmentEnvironment 3 The Command Prompt “..” is displayed in the Command Window. When the Command Window is active, a blinking cursor appears to the right of the prompt. The cursor and the prompt signify that Matlab is ready to perform a computationaloperation. The Workspace lists all the variables that you have created so far and their values. Other information is also displayed here, such as the maximum and mini- mumvaluesofanyvariablesthatarecreated. The Command History records all of the commands that you have previously typed at the Command Prompt. You can select one of these commands using the mouse and execute it in the Command Window by double-clicking it from within theCommandHistorywindow. CurrentFolder:YoucandirectMatlabtosetupafolderofyourchoicetobeacur- rentfolder.Thiswillthenbeyourworkingfolder,whereyoucansaveyourprograms. ThemainwindowthatcontainsthesefourwindowsiscalledtheMatlabDesktop. As mentioned earlier, the Matlab Desktop contains four windows: the Command Window, the Command History, the Current Folder, and the Workspace.When oneofthese windowsisactive,theremaining windows become inactive, but the contents of the remaining windows may still be updated if a script is running.Thetitle bar oftheactivewindow appearsina darkgray color,whereas thetitlebaroftheinactivewindowappearsinlightgraycolor.Intheprecedingfig- ure, the Command Window is active and the title bars of the other three windows aregrayedout(inactive). The Menu in the Matlab Desktop dynamically changes according to the win- dowselected(theactivewindow). ClickontheWorkspacewindowandnotethechangeintheMenu. Click another time on the Command History window and note the change in theMenu. 1.1.2 Creating Scalar Variables Matlab is a short name for Matrix laboratory. As the name indicates, Matlab is a matrix-based software package, which, infact, considers the scalar variable to be a 131matrix.Ascalarheremeansanumbersuchas“2”or“2100.” 4 MatlabbyExample Select Command Window by left-clicking on the Command Window. The Command Window prompt is “..” or “EDU..” for the educational version. To createascalarvariable,type“x51;”attheCommandPromptandthenpressEnter. ..x51; This command creates the scalar variable x and assigns the value “1” to it. Remember, the characters “..” are just the command prompt. The semicolon “;” is used to direct Matlab not to display the value of the variable x in the Command Window.Ifyouleavethesemicolonofftheendofacommand,thenitwillbeech- oed straightaway to the display, which can sometimes be cumbersome for very largearrays.Alternatively,itsometimescanbeusefultoseetheresultsdisplayed. Note the changes that happened in the Command Window, the Command History, and the Workspace windows. The Workspace displays the x variable, its value, and the maximum and minimum values of the variable. The Command Historyrecordsthex51;command. Double-click the variable x in the Workspace. The Variable Editor pops up and shows the value of the variable. To change the value of the variable x, double- click on the cell indicated by the black arrow in the following figure and change it to another value, for example, by typing the numeral “2”. Press Enter. Close the Variable Editor window by clicking the X at the top right of the Variable Editor window. Value MatlabIntegratedDevelopmentEnvironment 5 Youshouldgetthefollowingfigure. 1.1.3 Creating Vector Variables Tocreateavectorvariable,typetheMatlabcommand ..y5[2,3,6,9,11,8,5,3,2,21]; attheCommandPromptandthenpressEnter. Thiscommandcreatesavectorvariablewiththevalues y5[2,3,6,9,11,8,5,3,2,21]: TheMatlabdesktoprespondstothiscommandasshowninthefollowingfigure. Inordertodrawthevectorvariabley,clickontheyvariableintheWorkspaceso that it is highlighted as in the following figure, then go to Menu !Graphics! plot(y).Apop-upwindowappearsandplotsthevectory. 6 MatlabbyExample Exercise21 IntheWorkspacewindowdouble-clickthevariabley.TheVariableEditorpopsupandshows youthecontentsofthisvariable.Changethecontentsofthevectorytobeasfollows: 2,3,6,9,1,8,5,3,2,21 Drawthevector.Youshouldgetthefollowingfigure. 1.1.4 Creating Array Variables Tocreateanarrayvariable,typethefollowingMatlabcommand ..Z5[1,2;3,4]; attheCommandPromptandthenpressEnter. MatlabIntegratedDevelopmentEnvironment 7 Note and make sure that you include the two semicolons and the commas in the command. Thiscommandcreatesanarrayvariablewiththefollowingvalues: Z5 [1 2 3 4] The Matlab desktop responds as shown in the following figure. In this book, we willuseuppercaseletterstonamearrays. To draw the array variable Z, click on the Z variable in the Workspace so as to highlight it (as shown in the following figure), then go to Menu!Graphics! mesh(Z). A pop-up window appears and displays the array variable Z as a 3D mesh. An alternative to using the pop-up menu is to right-click on the Z array in theWorkspaceandselectmesh(Z)fromthatmenu. 8 MatlabbyExample Exercise31 In the Workspace, double-click the array variable Z. The Variable Editor pops up and shows you the contents of this variable. Change the contents of this variable to the following: Z5 [1 6 3 4] DrawthearrayvariableZ.Youshouldnowgetthefollowingfigure. Lesson 1.2 Matlab Script Files Objectives (cid:1) Tolearnhowtocreate,name,save,andexecuteMatlabscriptfiles. (cid:1) Tolearnhowtomakeyourcodereadableforothers. (cid:1) TolearnhowtocommentMatlabcode. Topics 1.2.1 CreatingaScriptFile 1.2.2 NamingaScriptFile 1.2.3 SavingaScriptFile 1.2.4 ExecutingaScriptFile 1.2.5 MatlabCodeReadability 1.2.6 CommentingMatlabCode MatlabIntegratedDevelopmentEnvironment 9 1.2.1 Creating a Script File AnM-fileisatextfilethatcontainsacollectionofcommandsthatMatlabexecutes inasequential order.Ascriptfilehasthefollowingproperties: (cid:1) Ithasnoarguments(inputdata)anditdoesnotreturnanyvalues(outputs). (cid:1) The commands executed in the script file have the same effect as if these commands wereexecutedintheCommandWindow. (cid:1) ThevariablescreatedbythescriptfilearedisplayedintheWorkspacewindow. Suppose that we would like to create a script file that contains the following Matlabcommands. x51; y52; Tocarryoutthistask,dothefollowing. LaunchMatlab.ThengotoMenu!File!New!Script. TheMatlabwindowEditorpopsup.Inthiswindow,typetheMatlabcommands shownintheEditor. 1.2.2 Naming a Script File Choose a name for this file. The extension for the file must be .m. The following restrictionsmustbetakenintoconsiderationwhenascriptfileisnamed. 10 MatlabbyExample (cid:1) Thefilenamemustnotcontainspacesorhyphens(-). (cid:1) Thefilenamemuststartwithanalphabeticalcharacter(a(cid:2)zorA(cid:2)Z). (cid:1) The file name must contain only alphabetical characters (a(cid:2)z or A(cid:2)Z), numbers (1(cid:2)9) orunderscores(_). (cid:1) Punctuationcharacterssuchascommas(,)orapostrophes(’)arenotallowed,because manyofthemhavespecialmeaningsinMatlab. (cid:1) ThefilenamemustbeneitheraMatlabvariablenoranexistingMatlabfunction. (cid:1) The use of a Matlab reserved word as a file name is not allowed. A list of Matlab reservedwordsaregivenbelow. 'name' 'across variable' 'node' 'build' 'output' 'description' 'parameter' 'descriptor' 'setup' 'element' 'signal' 'input' 'source' 'interface input' 'terminal' 'interface node' 'through variable' 'interface output' 'variable' 'item type' 'local variable' (cid:1) TheuseofaMatlabkeywordasafilenameisnotallowed.AlistofMatlabkeywords aregivenbelow. 'break' 'global' 'case' 'if' 'catch' 'otherwise' 'classdef' 'parfor' 'continue' 'persistent' 'else' 'return' 'elseif' 'spmd' 'end' 'switch' 'for' 'try' 'function' 'while' To check that the file name you have chosen is not a Matlab keyword or a Matlabfunction,youcanuseMatlabhelpandsearchunderyourchosenfilename. Forexample,letuschoosecat.masafilename.TypeattheCommandPrompt ..help cat Matlab responds and informs you that there is already a function called cat that concatenates arrays. So you should choose a different file name (and remember to check that this new name is not restricted in the same way too!). Matlab will warn against using names that are existing Matlab keywords, but it will not produce a warning when generating a script with certain function names, for example, the cat function above. Therefore, for this reason you should always test new user-defined names that you are unsure about by using the help facility, as shown previously, to avoidpotentialproblemswithnameclasheswhendebugging.

See more

The list of books you might like