Interacting With MATLAB 27 same as A,you get an error message Code2.3.4: 1>a Output2.3.4: 1???Undefined function or variable 'a'. MATLAB can,of course,tolerate lower-case variable names,so it is fine to assign a value to a: Code2.3.5: 1>a=3 Output 2.3.5: |>a= 3 In short,A and a are different variables.You can even carry out computations using your two variables,assigning a new variable to the result: Code2.3.6: I>>My Difference a -A Output 2.3.6: My_Difference The last example shows that the name of a variable need not be restricted to a single let ter.It can be a string such as My Difference.Spaces are not permitted in variable names or in names of programs or other files.However,spaces are useful for reading meaningful phrases like My Difference,so a subscript line can be used as a proxy for the space,as in My_Difference.Another method is to use uppercase letters to demarcate the words within compounds.This format is called"camelCase."(Think of what a camel looks like.The capital letter in the middle of the name is like a hump in the middle of a camel's back. Be aware that variable names can sart Neither ca they include specia cha cters 8.&e, AB. e names cannot use reserve f,Io
Interacting With MATLAB 27 If you ask MATLAB about the value of a variable called a , which you innocently believe is the same as A , you get an error message: Code 2.3.4: >> a Output 2.3.4: ??? Undefi ned function or variable 'a'. MATLAB can, of course, tolerate lower-case variable names, so it is fine to assign a value to a : Code 2.3.5: >> a = 3 Output 2.3.5: >> a = 3 In short, A and a are different variables. You can even carry out computations using your two variables, assigning a new variable to the result: Code 2.3.6: >> My_Difference = a - A Output 2.3.6: My_Difference = 1 The last example shows that the name of a variable need not be restricted to a single letter. It can be a string such as My_Difference . Spaces are not permitted in variable names or in names of programs or other files. However, spaces are useful for reading meaningful phrases like My Difference, so a subscript line can be used as a proxy for the space, as in My_Difference. Another method is to use uppercase letters to demarcate the words within compounds. This format is called „camelCase.‰ (Think of what a camel looks like. The capital letter in the middle of the name is like a hump in the middle of a camelÊs back.) Be aware that variable names cannot start with numbers. Neither can they include special characters ( $ , % , & , @ , - , + , * , / , \ , ^ , or the comma). Finally, variable names cannot use special, reserved words for MATLAB, like if , for , or end. You will encounter these reserved words later in this book. You neednÊt worry about remembering them at this stage
28 Interacting With MATLAB nor will you ever have to worry about this,for if you assign a variable to a reserved word in MATLAB,you will get an error message,with a helpful pointer()underneath the char- acter where MATLAB detected the error: Code2.3.7: 1>>for=4 Output 2.3.7: ???for=4: Error:The expression to the left of the equals sign is not a valid target for an assignment. This last example illustrates how relying on error messages can help you. the ina ntent use o the nam rd-to-track-down problem.as in the n average might be =(5+3+1)/3.This MATL e o to th hneea How you later tried A fail or 0 g ou had d to the varial =22/ that value would override ps built-in value of 3.14159. ctice to use descriptive variable n oid functi and variables that a alre dy defined in MATL AR IEV ou are in doubt about the name of a variable,as well should he at this stage of your learning (!)check by using the help command.For example.you could tyne heln mean or heln pi at the command promnt (>>Another strateey is to use variable names that are unlikely to be part of MATLAB's library,such as David Mean or Ion mean or Brad mean when in doubt.there is no harm in checking whether a name you are introducing has special status.You can do so by typing help followed by the name you are considering.If MATLAB replies that the name is unknown,you can use it safely. Must a variable name be supplied for the result of every new computation?The answer is No.When no output variable is declared,MATLAB automatically assigns the output to a variable called ans,short for"answer. Code 2.3.8: 1>>a+A Output2.3.8: ans 5
28 Interacting With MATLAB nor will you ever have to worry about this, for if you assign a variable to a reserved word in MATLAB, you will get an error message, with a helpful pointer (|) underneath the character where MATLAB detected the error: Code 2.3.7: >> for = 4 Output 2.3.7: ??? for = 4; | Error: The expression to the left of the equals sign is not a valid target for an assignment. This last example illustrates how relying on error messages can help you. In contrast to the check for misuse of reserved words as variable names, there is no automatic check against the inadvertent use of the name of a built-in MATLAB function or command as a variable name. This can create a very-hard-to-track-down problem, as in the following example. In computing an average, you might be tempted to write mean = (5+3+1)/3 . This would assign the value of 3.0 to the variable mean . However, if you later tried to use the built-in MATLAB function mean on another set of numbers, the operation would either fail or (arguably worse!) succeed but return a plausible, wrong value, in this case 3.0 , that you had previously assigned to the variable mean . Similarly, if you defined pi = 22/7 , that value would override pi Ês built-in value of 3.14159⁄ . So itÊs good practice to use descriptive variable names to avoid functions and variables that are already defined in MATLAB. If you are in doubt about the name of a variable, as well you should be at this stage of your learning (!), check by using the help command. For example, you could type help mean or help pi at the command prompt ( >> ). Another strategy is to use variable names that are unlikely to be part of MATLABÊs library, such as David_Mean or Jon_Mean or Brad_Mean . When in doubt, there is no harm in checking whether a name you are introducing has special status. You can do so by typing help followed by the name you are considering. If MATLAB replies that the name is unknown, you can use it safely. Must a variable name be supplied for the result of every new computation? The answer is No. When no output variable is declared, MATLAB automatically assigns the output to a variable called ans , short for „answer.‰ Code 2.3.8: >> a + A Output 2.3.8: ans = 5
Interacting With MATLAB 29 e was most recently assigned to Code2.3.9: I>>ans Output2.3.9: 24snme38rsupresngoupuyomtigorhctoingEndotLn Including or not including a semi-colon at the end of a line of code has an important effect Omitting the se on enables output to the Command window,at I least for operations thta value.Adding a semi-coon suppresses screen output for that operation. Code2.4.1: I>>My_Difference; Output 2.4.1: 1> Tha ahbe e e无2se If you do a new computation and follow it with a semi-colon,you again seem to get the same null effect: Code2.4.2: I>>My_Difference_2 =A-My_Difference; Output 2.4.2: 1> out,as you can confirm by typing Code2.4.3: I>>My_Difference_2
Interacting With MATLAB 29 You can inquire into the value of ans just as you can inquire into the value of any other variable. ans has whatever value was most recently assigned to it. Code 2.3.9: >> ans Output 2.3.9: ans = 5 2.4 Allowing or Suppressing Outputs by Omitting or Including End-of-Line Semi-Colons Including or not including a semi-colon at the end of a line of code has an important effect. Omitting the semi-colon enables output to the Command window, at least for operations that return a value. Adding a semi-colon suppresses screen output for that operation. For example, if you type My_Difference followed by a semi-colon, the result is initially disappointing. Code 2.4.1: >> My_Difference; Output 2.4.1: >> Apparently nothing happened. In a sense, this is true, because My_Difference already had a value assigned to it. That value was the one it took on earlier, via Code 2.3.6. If you do a new computation and follow it with a semi-colon, you again seem to get the same null effect: Code 2.4.2: >> My_Difference_2 = A - My_Difference; Output 2.4.2: >> However, the computation has, in fact, been carried out, as you can confirm by typing My_Difference_2 without a semi-colon at the end: Code 2.4.3: >> My_Difference_2
30 Interacting With MATLAB Output 2.4.3: My_Difference_2 1 Suppressing outputs by adding a semi-colon at the end of a command can be useful to pre. vent the printing in the Command window of a huge list of numbers that goes on"forever. You can break out of such as salvo of unwanted output by interrupting the program with ctrl-c,when the Command window is the active window.However,it is better to get into the habit of adding semi-colons to the ends of lines,removing them when you want to see the results of particular lines.The practice of including and omitting semi-colons at the ends of lines of code in MATLAB is so important that we have devoted an entire section to this one feature of MATLAB. 2.5 Correcting Errors in the Command Window What if you make an error in the Command window?Recently entered lines can be restored to the Command window using the up-arrow key.Hitting the up-arrow on the keyboard after the>prompt n times brings you back n command lines.For example,hitting the up ores th m t re command,whereupon it can be executed again after ,the line can be ne or more up arrows),and the ndthe A first letter,i t,if the ld like lin type ts firs cha lowed by the uparrow key one or more times. optional comments to show the up-arrow key's effects.What was intended was to add 15 to 13 (not to add 5 to 3)and then to show the results in the Command window: Code2.5.1: 1>>A■5: >>B=3: >C -A B;BOops!no output Output 2.5.1: 1>> Code2.5.2: I>>C=A B &restored by one up-arrow,then ';deleted
30 Interacting With MATLAB Output 2.4.3: My_Difference_2 = 1 Suppressing outputs by adding a semi-colon at the end of a command can be useful to prevent the printing in the Command window of a huge list of numbers that goes on „forever.‰ You can break out of such as salvo of unwanted output by interrupting the program with ctrl-c , when the Command window is the active window. However, it is better to get into the habit of adding semi-colons to the ends of lines, removing them when you want to see the results of particular lines. The practice of including and omitting semi-colons at the ends of lines of code in MATLAB is so important that we have devoted an entire section to this one feature of MATLAB. 2.5 Correcting Errors in the Command Window What if you make an error in the Command window? Recently entered lines can be restored to the Command window using the up-arrow key. Hitting the up-arrow on the keyboard after the >> prompt n times brings you back n command lines. For example, hitting the up arrow once restores the most recent command, whereupon it can be executed again after modification or correction if needed. If a line generates an error, the line can be restored (using one or more up arrows), and then edited before being executed again (this time correctly). The same procedure can be used to correct an error, say, three lines back, and then with judicious use of the up-arrow key and the mouse, the results can be corrected. A useful shortcut, if the line you would like to restore is several lines back and you know its first letter, is to type its first character followed by the up-arrow key one or more times. Trial-and-error correction is helpful when youÊre figuring out how to accomplish a particular operation. Here is an example, copied and pasted from the Command window, with optional comments to show the up-arrow keyÊs effects. What was intended was to add 15 to 13 (not to add 5 to 3) and then to show the results in the Command window: Code 2.5.1: >> A = 5; >> B = 3; >> C = A + B; %Oops! no output Output 2.5.1: >> Code 2.5.2: >> C = A + B %restored by one up-arrow, then ';' deleted
Interacting With MATLAB 31 Output 2.5.2: Code2.5.3: >A=15; &restored by 4 up-arrows,then 5 changed to 15 >>B 13 srestored by 4 up-arrows,then 3 changed to 13 >>c-A+B &Short cut!restored by typing c then one up-arrow Output2.5.3: c 28 2.6 Writing,Saving,and Running Larger Programs as Scripts(.m Files) Asalready mentioned,once your program gets complicated,in the sense that it doesn't fit into one or two nand lin s,it makes sense to compose and save the program as B SE or and t nen to run it rom th than typ y-line into the g program sc ally.This mean s that you can a金aad aving th you L To open the Editor window to modify an existing file or to create a new file.type edit in click on the Ne button If th f a file edit (follow )that file is tory.Otherwise w file by that nan ated in th pro ent din .By default.the filename is as med to have the.m extension.If no filename is specified.the new,as yet unsaved,file is called Untitled.m by default. When the Editor window is first opened,a blank screen appears.Our recommendation for how to proceed next is to write the name of the program as a comment a comment is a non-executable string.marked by a percent sign (to its left at the start of each line.We usually write the title of a program as a comment,then we immediately select and copy the title alone (i.e.,without the s sign).and finally we go to Save As,pasting the name of the program into the Save As dialog.Here is an example of a small program,saved as My_Program_01.m with a few comments.The second comment gives a general account of the purpose of the program.Writing such a comment is advisable. Code2.6.1: |号My_Program_01 &A program to add two numbers called x and Y
Interacting With MATLAB 31 Output 2.5.2: C = 8 Code 2.5.3: >> A = 15; %restored by 4 up-arrows, then 5 changed to 15 >> B = 13; %restored by 4 up-arrows, then 3 changed to 13 >> C = A + B %Short cut! restored by typing C then one up-arrow Output 2.5.3: C = 28 2.6 Writing, Saving, and Running Larger Programs as Scripts (.m Files) As already mentioned, once your program gets complicated, in the sense that it doesnÊt fit into one or two visible command lines, it makes sense to compose and save the program as a script using MATLABÊs Editor and then to run it from the Editor window rather than typing it in line-by-line into the Command window. Composing program scripts off-line lets you work on them incrementally. This means that you can add to them a little at a time after checking that each of the components works as expected. Saving the scripts lets you use them again later, either for the same purpose or for inspiration or reminders for future work. To open the Editor window to modify an existing file or to create a new file, type edit in the command line, or click on the New Script button. If the name of a file is put in after edit (following a space), that file is opened for editing, provided itÊs in the current directory. Otherwise, a new file by that name is created in the current directory. By default, the filename is assumed to have the .m extension. If no filename is specified, the new, as yet unsaved, file is called Untitled.m by default. When the Editor window is first opened, a blank screen appears. Our recommendation for how to proceed next is to write the name of the program as a comment. A comment is a non-executable string, marked by a percent sign ( % ) to its left at the start of each line. We usually write the title of a program as a comment, then we immediately select and copy the title alone (i.e., without the % sign), and finally we go to Save As, pasting the name of the program into the Save As dialog. Here is an example of a small program, saved as My_Program_01.m with a few comments. The second comment gives a general account of the purpose of the program. Writing such a comment is advisable. Code 2.6.1: % My_Program_01 % A program to add two numbers called X and Y