You can perform operations in MATLAB in two ways:
- In the interactive mode, in which all commands are entered directly in the Command window, or
- By running a MATLAB program stored in script file. This type of file contains MATLAB commands, so running it is equivalent to typing all the commands-one at a time-at the Command window prompt. You can run the file by typing its name at the Command window prompt.
Using the interactive mode is similar to using a calculator, but is convenient only for simpler problems. When the problem requires many commands, a repeated set of commands, or has arrays with many elements, the interactive mode is inconvenient. Fortunately, MATLAB allows you to write your own programs to avoid this difficulty. You write and save MATLAB programs in M-files, which have the extension. m; for example, program1. m
MATLAB uses two types of M-files: script files and function files. You can use the Editor Debugger built into MATLAB to create M-files. A script file contains a sequence of MATLAB commands, and is useful when to use many commands or arrays with many elements. Because they con tam commands, script files are sometimes called command files. You execute a script-file at the Command window prompt by typing its name without the extension.m.
Another type of M-file is a function file, which is useful when you need to repeat the operation of a set of commands. You can create your own function files.
Script files may contain any valid MATLAB commands or functions, including user-written functions. When you type the name of a script file at the Command window prompt, you get the same result as if you had typed at the Command window prompt all. the commands stored in the script file, one at a time. When you type the name of the script file, we say that you are “running the file” or “executing the file.” The values of variables produced by running a script file are available in the workspace; thus, we say the variables created by a script file are global variables.
Creating and Using a Script File
The symbol %designates a comment, which is not executed by MATLAB. Comments are not that useful for interactive sessions, and are used mainly in script files for the purpose of documenting the file. The comment symbol may be put anywhere in the line. MATLAB ignores everything to the right of the %symbol. For example, consider the following session.
Note that the portion of the line before the %sign is executed to compute x.
Here is a simple example that illustrates how to create, ‘save, and run a script file, using the Editor/Debugger built into MATLAB. However, you may use another text editor to create the file. The sample file is shown below. It computes the sine of the square root of several numbers and displays the results on the screen.
% Program example1.m
% This program computes the sine of
% the square root and displays the result.
x = sqrt ([5:2 :13] );
Y = sin(x)
To create this new M-file (in the MS Windows environment), in the Command window select New from the File menu, then select M-file. You will then see a new edit window. This is the Editor/Debugger window as shown in Figure 1.4-1. Type in the file as shown above. You can use the keyboard and the Edit menu in the Editor/Debugger as you would in most word processors to create and edit the file. When finished, select Save from the File menu in the Editor/Debugger. In the dialog box that appears, replace the default name provided (usually named Untitled) with the name example1 , and click on Save. The Editor/Debugger will automatically provide the extension . m and save the file in the MATLAB current directory, which for now we will assume to be on the hard drive.
Once the file has been saved, in the MATLAB Command window type the script file’s name example1 to execute the program. You should see the result displayed in the Command window. The session looks like the following.
0.7867 0.4758 0.1411 0.1741 -0.4475
Figure 1.4-1 shows a MATLAB MS Windows screen containing the resulting Command window display and the Editor/Debugger opened to display the script file.
Effective Use of Script Files
Create script fiIes to avoid the need to retype commonly used procedures. The above file, example1 implements a very simple procedure, for which we ordinarily would not create a script file. However, it illustrates how a script file is useful. For example, to change the numbers evaluated from [3: 2 : 11] to [2 : 5 : 27] , simply edit tile corresponding line and save the file again (a common oversight is to forget to resave the file after making changes to it).
Here are some other things to keep in mind when using script files:
- The name of a script file must follow the MATLAB convention for naming variables; that is, the name must begin with a letter. and may include dig and the underscore character. up to 31 characters.
- Recall that typing a variable’s name at the Command window prompt causes MATLAB to display the value of that variable. Thus, do not give a script file the same name as a variable it computes because MATLAB will not be able to execute that script file more than once. unless you clear the variable.
- Do not give a script file the same name as a MATLAB command or function. You can check to see if a command. function or file name already exists by using the exi s t command. For example, to see if a variable example1 already exists, type exist ( ‘example1’ ); this will return a 0 if the variable does not exist, and a I if it does. To see if an M-file example1 m already exists, type exist (‘ example1 .m file before creating the file; this will return a 0 if the file does not exist, and a if it does. Finally, to see if a built-in function example1 already exists, type exist ( ‘example1′ builtin’) before creating the file will return a 0 if the built-in function does not exist, and a 5 if it does.
- As in interactive mode, all variables created by a script file are global variables, which means that their values are available in the basic workspace. You can type who to see what variables are present.
- Variables created by a function file are local to that function, which mean that their values are not available outside the function. All the variables in a script file are global. Thus, if you do not need to have access to an the variables in a script file, consider using a function file instead. This will avoid “cluttering” the workspace with variable names, and will reduce memory requirements. Creation of user-defined function files is discussed.
- You can use the type command to view an M-file without opening it with a text editor. For example, to view the file examplel, the command is type examplel.
Note that not all functions supplied with MATLAB are “built-in” function. For example, the function mean.m is supplied but is not a built-in function. The command exist (‘ mean. m’, ‘file’ ) will return a 2, but the command exist (‘mean’, ‘builtin’) will return a O.You may think of builtin functions as primitives that form the basis for other MATLAB functions. You cannot view the entire file of a built-in function in a text editor. only the comments.
Effective Use of the Command and Editor/Debugger Window
Here are some tips on using the Command and Editor/Debugger window effectively.
- You can use the mouse to resize and move windows so they can be viewed simultaneously. Or you can dock the Editor/Debugger window inside the Desktop by selecting Dock from the view menu of the Editor/Debugger. To activate a window, click on it.
- If the Editor/Debugger is not docked, use the Alt- Tab key combination to switch back and forth quickly between the Editor/Debugger window and the Command window. In the Command window. use the up-arrow key to retrieve the previously typed script-file name, and press Enter to execute the script file. This technique allows you to check and correct your program quickly. After making changes in the script file, be sure to save it before switching to the Command window.
- You can use the Editor/Debugger as a basic word processor to write a short report that includes your script file, results, and discussion, perhaps present your solution to one of the problems. First use the mouse to highlight the results shown in the Command window, then copy and paste them to the Editor/Debugger window above or below your script file (use Copy and Paste on the Edit menu). Then, to save space, delete any extra blank lines, and perhaps the prompt symbol. Type your name arid any other required information, add any discussion you wish, and print the report from the Editor/Debugger window, or save it and import it into the word processor of your choice (change the file name or its extension if you intend
to use the script file again).
Debugging Script Files
Debugging a program is the process of finding and removing the “bugs,” or errors, in a program. Such errors usually fall into one of the following categories.
- Syntax errors such as omitting a parenthesis or comma, or spelling a command name incorrectly. MATLAB usually detects the more obvious errors and displays a message describing the error and its location.
- Errors due to an incorrect mathematical procedure, called runtime errors. They do not necessarily occur every time the program is executed; their occurrence often depends on the particular input data. A common example is division by zero.
MATLAB error messages usually allow you to find syntax errors. However, runtime errors are more difficult to locate. To locate such an error, try the following:
- Always test your program with a simple version of the problem, whose answers can be checked by hand calculations.
- Display any intermediate calculations by removing semicolons at the end of statements.
- Use the debugging features of the Editor/Debugger, which are covered. However, one advantage of MATLAB is that it requires relatively simple programs to accomplish many types of tasks. Thus you probably will not need to use the Debugger for many of the problems encountered in this text.
Comments may be put anywhere in the script file. However, it is important to note that the first comment line before any executable statement is the line searched by the Lookf o r command, . Therefore, if you intend to use the script file in the future, consider putting key words that describe the script file in this first line (called the HI line).
A suggested structure for a script file is the following.
- Comments section In this section put comment statements to give:
a. The name of the program and any key words in the first line.
b. The date created, and the creators’ names in the second line.
c. The definitions of the variable names for every input and output variable. Divide this section into at least two subsections, one for input data, and one for output data. A third, optional section may include definitions of variables used in the calculations. Be sure to include the units of meqsurement for all input and all output variables!
d. The name of every user-defined function called by the program.
- Input section In this section put the input data and/or the input functions ·that enable data to be entered. Include comments where appropriate for documentation.
- Calculation section Put the calculations in this section. Include comments where appropriate for documentation.
- Output section In this section put the functions necessary to deliver the output in whatever form required. For example, this section might contain functions for displaying the output on the screen. Include comments where appropriate for documentation.
- The programs in this text usually omit the comments in order to save space. These comments are not necessary here because the text discussion associated with the program provides the required documentation, and because we all know who wrote these programs!
Documenting Units of Measurement
We emphasize again that you must document the units of measurement for all the input and all the output variables. More than one dramatic failure of an engineering system has been traced to the misunderstanding of the units used for the input and output variables of the program used to design the system. Table 1.4-1 lists common units and their abbreviations. The foot-pound-second system (FPS) is also called the U.S. Customary System and the British Engineering System. SI (Systeme Internationale) is the international metric system.
Using Script Files to Store Data
a set of daily temperature measurements at a particular location, which are needed from time to time for calculations. As a short example, consider the following script file, whose name is my data. m.The array temp_F contains temperatures in degrees Fahrenheit.
% File mydata.m: Stores temperature data.
% Stores the array temp_F,
% which contains temperatures in degrees Fahrenheit.
temp_F ~ [72, 68, 75, 77, 83, 79)
A session to access this data from the Command window, and convert the temperatures
to degrees Celsius, is
temp _ F =
72 68 75 77 83 79
» temp _ C = 5 * ( temp_F – 32 ) / 9
temp _ C =
22.2222 20.0000 23.8889 25.0000 28.3333 26.1111
Thus 68° Fahrenheit corresponds to 20° Celsius
Controlling Input and Output
MATLAB provides several useful commands for obtaining input from the user and for formatting the output (the results obtained by executing the MATLAB commands). Table 1.4-2 summarizes these commands. The methods presented in this section are particularly useful with script files.
You already know how to determine the current value of any variable by t) ping its name and pressing Enter at the command prompt. However. this method. which is useful in the interactive mode, is not useful for script files. The disp function (short for “display”) can be used instead. Its syntax is di sp (A) , where A represents a MATL.A B variable name. Thus typing disp (Speed) causes the value of the variable Speed to appear on the screen, but not the variable’s name.
The disp function can also display text. You enclose the text within single quotes. For example, the command disp ( ‘The predicted speed is: ‘ ) causes the message to appear on the screen. This command can be used with the first form of the disp function in a script file as follows (assuming the value of Speed is 63):
dispt (‘The predict_ed speed is:’)
When the file is run, these lines produce the following on the screen:
The predicted speed is:
The input function displays text on the screen, waits for the user to enter something from the keyboard, and then stores the input in the specified variable. For example, the command x = input ( ‘Please enter the value of x:’) causes the message to appear on the screen. If you type 5 and press
Enter, the variable x will have the value 5.
A string variable is composed of text (alphanumeric characters). If you want to store a text input as a string variable, use the other form of the inpu t command. For example, the command Calendar = input (,Enter the day of the week:’ s “) prompts you to enter the day of the week. If you type Wednesday, this text will be Stored in the string variable Calendar.
Use the menu function to generate a menu of choices for user input. Its syntax
k = menu(‘title’, ‘option1’, ‘option2’, … )
The function displays the menu whose title is in the string variable ‘ title and whose choices are string variables’ option1′, ‘option2’, and soon. The returned value of k is I, 2,… depending on whether you click on the button for option1, option2, and so forth. For example, the following script uses a menu to select the data marker for a graph, assuming that the vectors x and y already exist.
k = menu(‘Choose a data marker’, ‘a’, ‘*’,’x’);
type = [‘ 0’ , ‘ *’ , ‘ x ‘):
plot (x,y,x,y,type (k)).