Sei sulla pagina 1di 7

4/3/12

Working with Functions in Files :: Program Files (MATLAB)

Working with Functions in Files


On this page Overview Types of Program Files Basic Parts of a Program File Creating a Program File Providing Help for Your Program Cleaning Up When the Function Completes

Overview
The MATLAB software provides a full programming language that enables you to write a series of MATLAB statements into a file and then execute them with a single command. You write your program in an ordinary text file, giving the file a name of f l n m . . The term you use for f l n m becomes the new command that MATLAB associates with the program. The file ieaem ieae extension of .mmakes this a MATLAB program file.

Types of Program Files


Program files can be scripts that simply execute a series of MATLAB statements, or they can be functions that also accept input arguments and produce output. MATLAB scripts: Are useful for automating a series of steps you need to perform many times. Do not accept input arguments or return output arguments. Store variables in a workspace that is shared with other scripts and with the MATLAB command line interface. MATLAB functions: Are useful for extending the MATLAB language for your application. Can accept input arguments and return output arguments. Store variables in a workspace internal to the function.

Basic Parts of a Program File


This simple function shows the basic parts of a program file. Any line that begins with %is not executable: fnto f=fc() ucin atn Fnto dfnto ln ucin eiiin ie %Cmueafcoilvle opt atra au. H ln 1 ie %FC()rtrstefcoilo N Hl tx ATN eun h atra f , ep et %uulydntdb N sal eoe y ! %Ptsml,FC()i PO(:) u ipy ATN s RD1N. f=po(:) rd1n; Cmet omn Fnto bd ucin oy

This table briefly describes each of these program file parts. Both functions and scripts can have all of these parts, except for the function definition line which applies to functions only. The sections that follow the table describe these parts in greater detail.

File Element Function definition line (functions only) H1 line

Description Defines the function name, and the number and order of input and output arguments A one line summary description of the program, displayed when you request h l on an entire folder, or when you use l o f r ep oko A more detailed description of the program, displayed together with the H1 line when you request h l on a specific function ep Program code that performs the actual computations and assigns values to any output arguments Text in the body of the program that explains the internal workings of the program

Help text

Function or script body

Comments

www.mathworks.in/help/techdoc/matlab_prog/f7-41453.html

1/7

4/3/12

Working with Functions in Files :: Program Files (MATLAB)

Function Definition Line The function definition line informs MATLAB that the file contains a function, and specifies the argument calling sequence of the function. This line contains the f n t o keyword and must always be the first line of the file, except for lines that are ucin nonexecutable comments. The function definition line for the f c function is at

All MATLAB functions have a function definition line that follows this pattern. Function Name. Function names must begin with a letter, can contain any alphanumeric characters or underscores, and must be no longer than the maximum allowed length (returned by the function n m l n t m x Because variables must a e e g h a ). obey similar rules, you can use the i v r a efunction to check whether a function name is valid: sanm ivraemfn sanm yu Function names also cannot be the same as any MATLAB keyword. Use the i k y o dfunction with no inputs to display a sewr list of all keywords. Although function names can be of any length, MATLAB uses only the first Ncharacters of the name (where Nis the number returned by the function n m l n t m x and ignores the rest. Hence, it is important to make each function name unique in aeegha) the first Ncharacters: N=nmlntmx aeegha N= 6 3 Note Some operating systems might restrict file names to shorter lengths.

The name of the text file that contains a MATLAB function consists of the function name with the extension . appended. m For example, aeaem vrg. If the file name and the function definition line name are different, MATLAB ignores the internal (function) name. Thus, if a e a e mis the file that defines a function named c m u e v r g , you would invoke the function by typing vrg. optAeae aeae vrg Note While the function name specified on the function definition line does not have to be the same as the file name, it is best to use the same name for both to avoid confusion. Function Arguments. If the function has multiple output values, enclose the output argument list in square brackets. Input arguments, if present, are enclosed in parentheses following the function name. Use commas to separate multiple input or output arguments. Here is the declaration for a function named s h r that has three inputs and three outputs: pee fnto [,y z =shr(ht,pi ro ucin x , ] peetea h, h) If there is no output, leave the output blank fnto piteut() ucin rnrslsx or use empty square brackets: fnto [ =piteut() ucin ] rnrslsx The variables that you pass to the function do not need to have the same name as the variables in the function definition line. The H1 Line The H1 line, so named because it is the first help text line, is a comment line immediately following the function definition line. Because it consists of comment text, the H1 line begins with a percent sign, % For the a e a efunction, the H1 line is . vrg %AEAEMa o vco eeet. VRG en f etr lmns This is the first line of text that appears when a user types h l f n t o n m at the MATLAB prompt. Further, the l o f r ep ucinae oko function searches on and displays only the H1 line. Because this line provides important summary information about the file, it is important to make it as descriptive as possible. Help Text
www.mathworks.in/help/techdoc/matlab_prog/f7-41453.html 2/7

4/3/12

Working with Functions in Files :: Program Files (MATLAB)

You can create online help for your program files by entering help text on one or more consecutive comment lines at the start of your program. MATLAB considers the first group of consecutive lines immediately following the H1 line that begin with %to be the online help text for the function. The first line without %as the left-most character ends the help. The help text for the a e a efunction is vrg %AEAEX,weeXi avco,i tema o vco VRG() hr s etr s h en f etr %eeet.Nnetriptrslsi a err lmns ovco nu eut n n ro. When you type h l f n t o n m at the command prompt, MATLAB displays the H1 line followed by the online help text ep ucinae for that function. The help system ignores any comment lines that appear after this help block. Note Help text in a program file can be viewed at the MATLAB command prompt only (using h l f n t o n m ). ep ucinae You cannot display this text using the MATLAB Help browser. You can, however, use the Help browser to get help on MATLAB functions and also to read the documentation on any MathWorks products. The Function or Script Body The function body contains all the MATLAB code that performs computations and assigns values to output arguments. The statements in the function body can consist of function calls, programming constructs like flow control and interactive input/output, calculations, assignments, comments, and blank lines. For example, the body of the a e a efunction contains a number of simple programming statements: vrg [,]=sz() mn iex; i ((m= 1 | ( = 1)| .. f ~( = ) | n = ) | . ( = 1& n= 1) %Fo cnrl m = & = ) lw oto err'nu ms b avco' %Errmsaedsly ro(Ipt ut e etr) ro esg ipa ed n y=smx/eghx; u()lnt() %Cmuainadasgmn optto n sinet Comments As mentioned earlier, comment lines begin with a percent sign (% Comment lines can appear anywhere in a program file, ). and you can append comments to the end of a line of code. For example, %Adu altevco eeet. d p l h etr lmns y=smx u() %Uetesmfnto. s h u ucin In addition to comment lines, you can insert blank lines anywhere in the file. Blank lines are ignored. However, a blank line can indicate the end of the help text entry for a program file. Block Comments. To write comments that require more than one line, use the block comment operators, % and % : { } % { Ti nx boko cd cek tenme o ipt hs et lc f oe hcs h ubr f nus pse i,mkssr ta ec ipti avlddt asd n ae ue ht ah nu s ai aa tp,adte bace t satpoesn tedt. ye n hn rnhs o tr rcsig h aa % } Note The % and % operators must appear alone on the lines that immediately precede and follow the block of help { } text. Do not include any other text on these lines.

Creating a Program File


You create files for your programs using a text editor. MATLAB provides a built-in editor, but you can use any text editor you like. Once you have written and saved the file, you can run the program as you would any other MATLAB function or command. The process looks like this:

www.mathworks.in/help/techdoc/matlab_prog/f7-41453.html

3/7

4/3/12

Working with Functions in Files :: Program Files (MATLAB)

Using Text Editors Program files are ordinary text files that you create using a text editor. If you use the MATLAB Editor/Debugger, open a new file by selecting New > File from the File menu at the top of the MATLAB Command Window. Another way to edit a program file is from the MATLAB command line using the e i function. For example, dt

ei fo dt o
opens the editor on the file f o m Omitting a file name opens the editor on an untitled file. o.. You can create the f c function shown in Basic Parts of a Program File by opening your text editor, entering the lines at shown, and saving the text in a file called f c . in your current folder. atm Once you have created this file, here are some things you can: List the names of the files in your current folder: wa ht List the contents of file f c . : atm tp fc ye at Call the f c function: at fc() at5 as= n 10 2 A Word of Caution on Saving Program Files Save any files you create and any MathWorks supplied files that you edit in folders outside of the folder tree in which the MATLAB software is installed. If you keep your files in any of the installed folders, your files can be overwritten when you install a new version of MATLAB. MATLAB installs its software into folders under m t a r o / o l o . To see what m t a r o is on your system, type albottobx albot m t a r o at the MATLAB command prompt. albot Also note that locations of files in the m t a r o / o l o folder tree are loaded and cached in memory at the beginning of albottobx each MATLAB session to improve performance. If you save files to m t a r o / o l o folders using an external editor, or albottobx if you add or remove files from these folders using file system operations, enter the commands c e rf n t o n m and la ucinae r h s t o b x before you use the files in the current session. eah olo For more information, see the r h s function reference page or the section Toolbox Path Caching. eah

Providing Help for Your Program


You can provide user information for the programs you write by including a help text section at the beginning of your program file. (See Help Text). You can also make help entries for an entire folder by creating a file with the special name C n e t . that resides in the otnsm folder. This file must contain only comment lines; that is, every line must begin with a percent sign. MATLAB displays the lines in a C n e t . file whenever you type otnsm hl flenm ep odrae C n e t . files are optional. If you have a folder that is on the path that does not contain a C n e t . file, MATLAB otnsm otnsm displays the first comment line (the "H1" line) of each . file in response to typing h l f l e n m . If you do not want to m ep odrae display any help summaries at all, create an empty an empty C n e t . file in that folder. When an empty C n e t . file otnsm otnsm exists, typing h l f l e n m causes MATLAB to respond with N h l f u d f r f l e n m . ep odrae o ep on o odrae. To get help in creating and validating your C n e t . files, you can use the Contents Report tool in the Current Folder otnsm
www.mathworks.in/help/techdoc/matlab_prog/f7-41453.html 4/7

4/3/12

Working with Functions in Files :: Program Files (MATLAB)

browser. See Displaying and Updating a Report on the Contents of a Folder for more information.

Cleaning Up When the Function Completes


When you have programmed all that you set out to do in your file, there is one last step to consider before it is complete. Make sure that you leave your program environment in a clean state that does not interfere with any other program code. For example, you might want to Close any files that you opened for import or export. Restore the MATLAB path. Lock or unlock memory to prevent or allow erasing MATLAB function or MEX-files. Set your working folder back to its default if you have changed it. Make sure global and persistent variables are in the correct state. MATLAB provides the o C e n pfunction for this purpose. This function, when used within any program, establishes a nlau cleanup routine for that function. When the function terminates, whether normally or in the event of an error or Ctrl+C, MATLAB automatically executes the cleanup routine. The following statement establishes a cleanup routine c e n p u for the currently running program: lauFn cenpb =oCenp@lauFn; lauOj nlau(cenpu) When your program exits, MATLAB finds any instances of the o C e n pclass and executes the associated function nlau handles. The process of generating and activating function cleanup involves the following steps: 1. Write one or more cleanup routines for the program under development. Assume for now that it takes only one such routine. 2. Create a function handle for the cleanup routine. 3. At some point, generally early in your program code, insert a call to the o c e n pfunction, passing the function nlau handle. 4. When the program is run, the call to o C e n pconstructs a cleanup object that contains a handle to the cleanup nlau routine created in step 1. 5. When the program ends, MATLAB implicitly clears all objects that are local variables. This invokes the destructor method for each local object in your program, including the cleanup object constructed in step 4. 6. The destructor method for this object invokes this routine if it exists. This perform the tasks needed to restore your programming environment. You can declare any number of cleanup routines for a program file. Each call to o C e n pestablishes a separate cleanup nlau routine for each cleanup object returned. If, for some reason, the object returned by o C e n ppersists beyond the life of your program, then the cleanup routine nlau associated with that object is not run when your function terminates. Instead, it will run whenever the object is destroyed (e.g., by clearing the object variable). Your cleanup routine should never rely on variables that are defined outside of that routine. For example, the nested function shown here on the left executes with no error, whereas the very similar one on the right fails with the error, U d f n d f n t o o v r a l ' ' This results from the cleanup routine's reliance on variable kwhich is defined neie ucin r aibe k. outside of the nested cleanup routine: fnto tsCenp ucin etlau k=3 ; mFn yu fnto mFn ucin yu frnf' i %\' k pit(k s dn, ) ed n ed n fnto tsCenp ucin etlau k=3 ; oj=oCenp@yu) b nlau(mFn; fnto mFn ucin yu frnf' i %\' k pit(k s dn, ) ed n ed n

Examples of Cleaning Up a Program Upon Exit Example 1 Close Open Files on Exit. MATLAB closes the file with identifier f dwhen function o e F l S f l i pnieaey terminates: fnto oeFlSfl(ieae ucin pnieaeyflNm) fd=fpnflNm,''; i oe(ieae r) c=oCenp@)coefd) nlau((fls(i); s=fedfd; ra(i) . . . ed n Example 2 Maintain the Selected Folder. This example preserves the current folder whether f n t o T a M y r o ucinhtaErr returns an error or not:
www.mathworks.in/help/techdoc/matlab_prog/f7-41453.html 5/7

4/3/12

Working with Functions in Files :: Program Files (MATLAB)

fnto cagFleSfl(ieae ucin hneodraeyflNm) cretodr=pd urnFle w; c=oCenp@)dcretodr) nlau((c(urnFle); fntoTaMyro; ucinhtaErr ed %ceeue c(urnFle)hr. n xcts dcretodr ee Example 3 Close Figure and Restore MATLAB Path. This example extends the MATLAB path to include files in the toolbox\images folders, and then displays a figure from one of these folders. After the figure displays, the cleanup routine r s o e e vcloses the figure and restores the path to its original state: etr_n fnto soIaeusdPt(mgFl) ucin hwmgOtieahiaeie fg =fgr; i1 iue igah=gnah[albot'tobxiae') mpt ept(mtaro \olo\mgs]; %Dfn tecenpruie eie h lau otn. cenpb =oCenp@)etr_n(i1 igah) lauOj nlau((rsoeevfg, mpt); %Mdf tept t gi acs t teiaefl, oiy h ah o an ces o h mg ie %addslyteiae n ipa h mg. adahigah; dpt(mpt) rb=ira(mgFl) g mediaeie; frnf'n Oeigtefgr %\' iaeie; pit(\ pnn h iue sn, mgFl) iaerb; mg(g) pue2; as() %Ti i tecenpruie hs s h lau otn. fnto rsoeevfgade nwah ucin etr_n(ihnl, ept) ds ' Coigtefgr' ip lsn h iue coefgade; ls(ihnl) pue2 as() ds ' Rsoigtept' ip etrn h ah rpt(ept) mahnwah; ed n ed n Run the function as shown here. You can verify that the path has been restored by comparing the length of the path before and after running the function: oiLn=lnt(ah; rge eghpt) soIaeusdPt(gen.p' hwmgOtieah'resjg) Oeigtefgr gen.p pnn h iue resjg Coigtefgr lsn h iue Rsoigtept etrn h ah crLn=lnt(ah; ure eghpt) crLn= oiLn ure = rge as= n 1 Retrieving Information About the Cleanup Routine In Example 3 shown above, the cleanup routine and data needed to call it are contained in a handle to an anonymous function: @)etr_n(i1 igah (rsoeevfg, mpt) The details of that handle are then contained within the object returned by the o C e n pfunction: nlau cenpb =oCenp@)etr_n(i1 igah) lauOj nlau((rsoeevfg, mpt); You can access these details using the t s property of the cleanup object as shown here. (Modify the ak s o I a e u s d P t function by adding the following code just before the comment line that says, "% T i i t e hwmgOtieah hs s h c e n p r u i e ") lau otn. ds ' Dslyn ifrainfo tefnto hnl: ip ipaig nomto rm h ucin ade' ts =cenpb.ak ak lauOjts; fn=fntosts) u ucin(ak wp=fnwrsae21 s u.okpc{,} frnf'n) pit(\'; pue2; as() Run the modified function to see the output of the f n t o scommand and the contents of one of the w r s a ecells: ucin okpc soIaeusdPt(gen.p' hwmgOtieah'resjg) Oeigtefgr gen.p pnn h iue resjg Dslyn ifrainfo tefnto hnl: ipaig nomto rm h ucin ade fn= u
www.mathworks.in/help/techdoc/matlab_prog/f7-41453.html 6/7

4/3/12

Working with Functions in Files :: Program Files (MATLAB)

fnto:'(rsoeevfg,mpt) ucin @)etr_n(i1igah' tp:'nnmu' ye aoyos fl:':wr\6m ie c\okg.' wrsae {x cl} okpc: 21 el wp= s iaeie 'resjg mgFl: gen.p' fg:1 i1 igah [x97ca] mpt: 135 hr cenpb:[x oCenp lauOj 11 nlau] rb [0x0x un8 g: 30503 it] ts:@)etr_n(i1igah ak (rsoeevfg,mpt) Coigtefgr lsn h iue Rsoigtept etrn h ah Using onCleanup Versus try-catch Another way to run a cleanup routine when a function terminates unexpectedly is to use a t y a c statement. There are r -c t h limitations to using this technique however. If the user ends the program by typing Ctrl+C, MATLAB immediately exits the t yblock, and the cleanup routine never executes. The cleanup routine also does not run when you exit the function r normally. The following program cleans up if an error occurs, but not in response to Ctrl+C: fnto cenpyac ucin lauBCth ty r pue1) as(0; cth ac ds( ip' Cletn ifrainaotteerr) olcig nomto bu h ro' ds( ip' Eeuigcenptss) xctn lau ak' ed n Unlike the t y a c statement, the o C e n pfunction responds not only to a normal exit from your program and any r -c t h nlau error that might be thrown, but also to Ctrl+C. This next example replaces the t y a c with o C e n p r -c t h nlau: fnto cenpyuc ucin lauBFn oj=oCenp@). b nlau((.. ds( ip' Eeuigcenptss); xctn lau ak') pue1) as(0; onCleanup in Scripts o C e n pdoes not work in scripts as it does in functions. In functions, the cleanup object is stored in the function nlau workspace. When the function exits, this workspace is cleared thus executing the associated cleanup routine. In scripts, the cleanup object is stored in the base workspace (that is, the workspace used in interactive work done at the command prompt). Because exiting a script has no effect on the base workspace, the cleanup object is not cleared and the routine associated with that object does not execute. To use this type of cleanup mechanism in a script, you would have to explicitly clear the object from the command line or another script when the first script terminates.

1984-2012- The MathWorks, Inc.

Site Help - Patents Piracy - RSS

Trademarks

Privacy Policy

Preventing

www.mathworks.in/help/techdoc/matlab_prog/f7-41453.html

7/7

Potrebbero piacerti anche