You are on page 1of 8

" ",

-

--~-------- .......

4

Script M-Files

For simple problems, entering your requests at the MATLAB prompt in the Command window is fast and efficient. However, as the number of commands increases, or when you wish to change the value of one or more variables and reevaluate a number of commands, typing at the MATLAB prompt 'quickly becomes tedious. MATLAB provides a logical solution to this problem. It allows you 10 place MATLAB commands in a simple text file and then tell MATLAB to open the file and evaluate the commands exactly as it would have if you had typed the commands at the MATLAB prompt. These files are called script files or M·files. The term "script" signifies that MATLAB simply reads from the script found in the file. The term M -file means that script filenames must end with the extension ' . m ' , as in, for example, examp 1 el. m.

4.1 SCRIPT M·FILE USE

To create a script M-file. click on the blank page icon on the MATLAB desktop toolbar, or choose New from the File menu and select M·tile. This procedure brings up a text editor window wherein you can enter MATLAB commands. The following script M-file shows the commands from an example considered earlier:

% script M-file examplel.m

erase~s ~ 4; % number of each item pads"" 6;

tape 2;

30

Section 4.1

Script M-File Use

31

items ~ erasers + pads + tape

cost = erasers*25 + pads*52 + tape*99 average_cost = cost/items

This file can be saved to disk and executed immediately hy (1) choosing Save and Run from the Debug menu, (2) pressing the Save and Run button on the Editor toolbar, or (3) simply pressing the function key FS. Alternatively, you can save this file as the M-file exampl,e1.m on your disk by choosing Save from the File menu; then, at the MATLAB prompt, irs just a matter of typing the name of the script file without the. m extension:

» examplel items =

12

cost =

610

average_cost 50.833

When MATLAB interprets the examp 1 el statement. it follows the search path described in Chapter 3. In brief. MATLAB prioritizes current MATLAB variables ahead of M-fiIe names. If example! is not a current MATLAB variable or built-in function name, MATLAB opens the file examplel. m (if it can find it) and evaluates the commands found there just as if they had been entered directly at the Command window prompt. As a result. commands within the M-file have access to all of the variables in the MATLAB workspace, and all of the variables created by the M-file become part of the workspace. Normally, the M-file commands are not displayed as t hey are eval ua ted. The echo on comma nd tells M A TLA B to displa y. or echo. co11J.mands to the Command window as they are read and evaluated. You can probably guess what the echo off command does. Similarly. the command echo by itself toggles the echo state.

This ability to create script M-files makes it simple to answer "what if?" questions. For example. you could repeatedly open the example1.m M-fiIe. change the number of erasers. pads. or tape, and then save and execute the file.

The utility of MATLAB comments is readily apparent when you use script files. as shown in examp 1 el. m. Comments allow you to document' the commands found in a script file. so that you do not forget the commands when you view them in the future. In addition. the use of semicolons at the ends of lines to suppress the display of results allows you to control script-file output. so that only important results are shown. Because of the utility of script files. MATLAB provides several functions that are particularly he lpfu! when used in M-file-s:

L

32

Script M-Files

Chapter 4

Function Description
beep Makes computer beep
disp(variablename) Displays results without identifying variable names
echo Controls Command window echoing of script file contents
as they are executed
input Prompts user for input
keyboard Temporarily gives control to keyboard. (Type return to
return control to the executing script M-fiIe.)
pause or pause(n) Pauses until user presses any keyboard key, or pauses for n
seconds and then continues
waitforbuttonpress Pauses until user presses mouse button or any keyboard key When a MATLAB command-is not terminated by a semicolon, the results are displayed in the Command window;with the variable name identified. For a prettier display, it is sometimes convenient to suppress the variable name. In MATLAB, this is accomplished with the command di sp:

» items items =

12

» disp(items) 12

Rather than repeatedly edit a script file for computations for a variety of cases, you can employ the input command to prompt for input as a script file is executed. For example, reconsider the examp 1 el. m script file, with the folfowing modifications:

% script M-file examplel.m

erasers = 4; % Number of each item pads = 6;

tape = input('Enter the number of rolls of tape purchased> '); items = erasers + pads + tape

cost = erasers*25 + pads*52 + tape*99 average_cost = cost/items

Section 4.1

Script M-file Use

33

Running this script M-file produces this result:

» example1

Enter the number of rolls of tape purchased> 3 items

13

cost =

709

average_cost 54.538

1n response to the prompt. the number 3 was entered and the Retum or Enter key was pressed. The remaining commands were evaluated as before. The function input accepts any valid MATLAB expression for input. For example, running the script file again and providing different input gives the following result:

» example!

Enter the numbe r of roll s of tape pur.chased > round( sq rt(13)) -1 items

13

cost =

709

average_cost 54.538

in this case. the number of rolls of tape was set equal to the result of evaluating the expression

round (sqrt(13))-1.

To see the effect of the echo command. add it to the script file and execute it:

erasers

4; % Number of each item

% script M-file examplel.m echo on

pads tapE:



,.

input('Enter the number of rolls of tape purchased> ');

items ~ erasers + pads + tape

_-------

34

Chapter 4

Script M-Fijes

cost = erasers*25 + pads*52 + tape*99 average_cost = cost/items

echo off

» examplel

erasers = 4; % Number of each item pads 6;

tape ;nput('Enter the number of rolls of tape purchased> ');

Enter the number of rolls of tape purchased> 2

items items =

erasers + pads + tape

12

cost erasers*25 + pads·52 + tape*99

cost

610

average_cost average_cost 50.833 echo off

cost/items

As you can see, the echo command made the result much harder to read. On the other hand, the echo command can be very helpful when debugging more complicated script files.

4.2 BLOCK COMMENTS AND CODE CEllS

In prior versions of MATLAB, comments were line oriented. That is, comments began with an initial percent sign and continued to the end of the current line. To continue the comments on the next line required another initial percent sign. Therefore, a block of comments would all start with initial percent signs, as shown here:

% This ;s an example of multiple line comments

% in an M-file. Each line requires an initial % sign or MATLAB % assumes the line contains code to be executed.

Section 4.3

Setting Execution Time

35

While the block of comments is visually simple. it can become cumbersome to manage later. when comment text is augmented or edited. In this case, the percent signs must remain at the beginnings of the lines. and the comment text must flow after the initial percent signs on each line. In the past. to make it less cumbersome. the MATLAB editor included commands for adding or removing the initial percent signs on a highlighted block of lines. Now. MATLAB 7 supports block comments through the use of the syntax %{ and %}. These symbols mark the beginning and end. respectively. of a block of text to be treated as comments by MATLAB. For example. using block comment syntax on the previous example produces

%{

This is an example of multiple line comments

in an M-file. Each line requires an initial % sign or MATLAB assumes the line contains code to be executed.

(Now lines can be added and edited as desired without having to place percent signs at the beginning of each line.)

%}

In addition to their utility in composing multiline comments. block comments will allow you to rapidly turn on and off the interpretation and execution of any number of lines of code in an Msfile. This feature is particularly helpful in creating and debugging large M-files. Simply adding %{ before and %} after a block of MATLAB code turns the enclosed code into comments that are not processed by MATLAB. When this feature is used, different sections of a script file can be executed at different times during the editing and debugging processes.

In the past. the MATLAB editor offered commands for executing a block of highlighted code in an editor window. In MATLAB 7. the editor now supports the selective execution of M-file code through the use of code cells. A code cell is simply

a block of M-file code that starts with a comment line containing two percent signs followed by a space (i.e .. %% ). The code cell continues to the end of the M-file or to .I •. the beginning of another code cell. From within the MATLAB editor. cells can be created. individually executed. and sequentially executed. thereby enabling effective M-file debugging. The Cell menu in the Editor window facilitates these operations. It is important to note that the syntax for code cells is interpreted by the editor. not by the MATLAB command interpreter. As a result. when an M-fik is executed after its name has been entered in the C ommaud window. code-eel! syntax

is ignored. and ail executable lines in the file are processed.

4.3 SETTING EXECUTION TiME

When ~t1E narr.e C~· an \1-fli~ ~5 tY:Jcc. i.~ I11c ,~~J.7f:J-!:[!!j{. window prompt. tht- ~"i-t'tl~ .s e:.:cC~_~ :-:c·. : !.~.~ :-:!~ cia ~c 1 ~'.. i n S0~:~ ~ c: rcum ~;_F~-~::': s ' ~ r.c i. E·.~ I a ~-g:l:' ~ 1"0 E.L~<.HE !yj ~.~ ~ pi ,-i.; . 2'~:::_

~-~---- -~---- ..... --- .-

36

Chapter 4

Script M-Fites

or situations wherein the data to be manipulated becomes available only over a long period of time while MATLAB is running), it is convenient to specify execution times for M-files. In MATLAB, this capability is accomplished by using timer objects. A timer object is created with the function timer. For example,

» my_timer ~ timer('TimerFcn' ,'Mfi7eName', 'StartDelay',lOO)

creates the timer object stored in the variable my_timer, which executes the M-tile MfileName 100 seconds after the timer has been started by using the start function:

» start(my_timer) % start the timer in the variable my_timer

In general terms, timer function syntax has the form

» t==timer(' PropertyNamel' .Prooertyvs 7uel, 'PropertyName2 ' ,PropertyVa 7ue2, .•. )

where the arguments identify property names as character strings paired with corresponding property values.

Neither MATLAB nor the computer operating system is held up while a timer is running, but not executing code. MATLAB and other programs can be used during this idle time. When the timer object initiates code execution. the timer takes control of MATLAB and executes the code, just as if the code had been typed at the MATLAB prompt. When this execution ends, MATLAB returns control to the Command window prompt.

The timer object has many more features. For example, . MfileName' can be any statement executable at the MATLAB prompt. It can be a script M-file, a function handle or function M-file, or a set of MATLAB commands, You also canspecify that timer code be executed on a periodic basis or executed a specified number of times. You can specify four different M-files or code sequences to be executed under different conditions .. For example,

» my_ti mer == timer( 'TimerFcn' , 'Mfi lel' , .

'StartFcn','Mfi7e2' , .

'Stopfcn,~ 'Mfi7e3', .

• ErrorFcn' , • Mfi 7e4');

creates a timer function that executes (1) 'Mfi 1 el' as the primary timer code that may be repeatedly executed. (2) 'Mfi 1 e2' when the timer is started with the start function, (3) 'Mfi 1 e 3' when the timer is stopped with the stop function, and (4) 'Mfi 1 e4' if a MATLA B error occurs while any of these functions are executing. (See the MATLAB documentation for more complete information about timer objects.)

--

Section 4.4

Startup and Finish

37

4.4 STARTUP AND FINISH

When MATLAB starts up. it executes two script M-files. matl abrc. m and startup. m. The first. matlabrc. m, comes with MATLAB and generally should not be modified. The commands in this M-file set the default Figure window size and placement. as well as a number of other default features, The default MATLAB search path is set by retrieving the script file pathdef. m from matlabrc.m. The Path Browser and Command window functions for editing the MATLAB search path maintain the file pathdef . m, so there is no need to edit it with a text editor.

Commands in mat 1 ab rc. m check for the existence of the script M-fiJe sta rtup. m on the MATLAB search path. If the M-file exists. the commands in it are executed. This optional M-file startup. m typically contains commands that add personal default features to MATLAB. For example. it is common to put one or more addpath or path commands in startup. m to append additional directories to the M ATLAB search path. Similarly. the default number-display format can be changed (e.g .. format compact). Since startup.m is a standard script Mfile. there are no restrictions as to what commands can be placed in it. (However. irs probably not wise \0 include Ihe command quit in startup.m!) On singleuser installations. startup. m is commonly stored in the tool box/l oca 1 subdirectory on the MATLAB path. On network installations, a convenient location for your startup.m file is the default directory where you start MATLAB sessions.

When you terminate MATLAB via the Exit MATLAB item on the File menu in the MATLAB desktop window (or by typing exit or quit at the MATLAB prompt) MATLAB searches the MATLAB path for a script M-fiIe named finish.m. If one is found. the commands in it are executed before MATLAB terminates. For example. the following fi ni sh • m prompts the user for confirmation before quilting. and the command qui t cancel provides a 'way to cancel quitting:

%FINISH Confirm Desire for Quitting MATLAB

question = 'Are You Sure You Want To Quit?';

button questdlg(question, 'Exit Request', 'Yes', 'No'. 'No');

switch button

case 'No'

quit cancel; % how to cancel quitting! end

% 'Yes' lets s cr-iot and MATlAB end.

You might also like