Using MATLAB (779505), страница 73
Текст из файла (страница 73)
They’re useful for automating series of MATLAB commands, suchas computations that you have to perform repeatedly from the command line.Scripts operate on existing data in the workspace, or they can create new dataon which to operate. Any variables that scripts create remain in the workspaceafter the script finishes so you can use them for further computations.Simple Script ExampleThese statements calculate rho for several trigonometric functions of theta,then create a series of polar plots.% An M–file script to produce% "flower petal" plotstheta = –pi:0.01:pi;rho(1,:) = 2*sin(5*theta).^2;rho(2,:) = cos(10*theta).^3;rho(3,:) = sin(theta).^2;rho(4,:) = 5*cos(3.5*theta).^3;for k = 1:4polar(theta,rho(k,:))pauseend% Comment lines% Computations% Graphics outputTry entering these commands in an M-file called petals.m.
This file is now aMATLAB script. Typing petals at the MATLAB command line executes thestatements in the script.After the script displays a plot, press Return to move to the next plot. Thereare no input or output arguments; petals creates the variables it needs in theMATLAB workspace. When execution completes, the variables (i, theta, andrho) remain in the workspace.
To see a listing of them, enter whos at thecommand prompt.17-717M-File ProgrammingFunctionsFunctions are M-files that accept input arguments and return outputarguments. They operate on variables within their own workspace. This isseparate from the workspace you access at the MATLAB command prompt.This section covers the following topics regarding functions:• “Simple Script Example”• “Basic Parts of a Function M-File”• “Function Names”• “How Functions Work”• “Checking the Number of Function Arguments”• “Passing Variable Numbers of Arguments”Simple Function ExampleThe average function is a simple M-file that calculates the average of theelements in a vector.function y = average(x)% AVERAGE Mean of vector elements.% AVERAGE(X), where X is a vector, is the mean of vector elements.% Non-vector input results in an error.[m,n] = size(x);if (~((m == 1) | (n == 1)) | (m == 1 & n == 1))error('Input must be a vector')endy = sum(x)/length(x);% Actual computationIf you would like, try entering these commands in an M-file called average.m.The average function accepts a single input argument and returns a singleoutput argument.
To call the average function, enterz = 1:99;average(z)ans =5017-8FunctionsBasic Parts of a Function M-FileA function M-file consists of:• “The Function Definition Line”• “The H1 Line”• “Help Text”• “The Function Body”• “Comments”The Function Definition LineThe function definition line informs MATLAB that the M-file contains afunction, and specifies the argument calling sequence of the function. Thefunction definition line for the average function isfunction y = average(x)input argumentfunction nameoutput argumentkeywordAll MATLAB functions have a function definition line that follows this pattern.If the function has multiple output values, enclose the output argument list insquare brackets.
Input arguments, if present, are enclosed in parentheses. Usecommas to separate multiple input or output arguments. Here’s a morecomplicated example.function [x,y,z] = sphere(theta,phi,rho)If there is no output, leave the output blankfunction printresults(x)or use empty square bracketsfunction [] = printresults(x)The variables that you pass to the function do not need to have the same nameas those in the function definition line.17-917M-File ProgrammingThe H1 LineThe H1 line, so named because it is the first help text line, is a comment lineimmediately following the function definition line.
Because it consists ofcomment text, the H1 line begins with a percent sign, “%.” For the averagefunction, the H1 line is% AVERAGE Mean of vector elements.This is the first line of text that appears when a user types help function_nameat the MATLAB prompt. Further, the lookfor function searches on anddisplays only the H1 line. Because this line provides important summaryinformation about the M-file, it is important to make it as descriptive aspossible.Help TextYou can create online help for your M-files by entering text on one or morecomment lines, beginning with the line immediately following the H1 line.
Thehelp text for the average function is% AVERAGE(X), where X is a vector, is the mean of vector elements.% Nonvector input results in an error.When you type help function_name, MATLAB displays the comment linesthat appear between the function definition line and the first non-comment(executable or blank) line. The help system ignores any comment lines thatappear after this help block.For example, typing help sin results inSINSine.SIN(X) is the sine of the elements of X.The Function BodyThe function body contains all the MATLAB code that performs computationsand assigns values to output arguments.
The statements in the function bodycan consist of function calls, programming constructs like flow control andinteractive input/output, calculations, assignments, comments, and blanklines.17-10FunctionsFor example, the body of the average function contains a number of simpleprogramming statements.[m,n] = size(x);if (~((m == 1) | (n == 1)) | (m == 1 & n == 1)) % Flow controlerror('Input must be a vector') % Error message displayendy = sum(x)/length(x);% Computation and assignmentCommentsAs mentioned earlier, comment lines begin with a percent sign (%). Commentlines can appear anywhere in an M-file, and you can append comments to theend of a line of code. For example,% Add up all the vector elements.y = sum(x)% Use the sum function.The first comment line immediately following the function definition line isconsidered the H1 line for the function.
The H1 line and any comment linesimmediately following it constitute the online help entry for the file.In addition to comment lines, you can insert blank lines anywhere in an M-file.Blank lines are ignored. However, a blank line can indicate the end of the helptext entry for an M-file.Function NamesMATLAB function names have the same constraints as variable names.MATLAB uses the first 31 characters of names. Function names must beginwith a letter; the remaining characters can be any combination of letters,numbers, and underscores. Some operating systems may restrict functionnames to shorter lengths.The name of the text file that contains a MATLAB function consists of thefunction name with the extension .m appended.
For example,average.mIf the filename and the function definition line name are different, the internalname is ignored.17-1117M-File ProgrammingThus, while the function name specified on the function definition line does nothave to be the same as the filename, we strongly recommend that you use thesame name for both.How Functions WorkYou can call function M-files from either the MATLAB command line or fromwithin other M-files. Be sure to include all necessary arguments, enclosinginput arguments in parentheses and output arguments in square brackets.This section provides the following information on calling MATLAB functions:• “Function Name Resolution”• “What Happens When You Call a Function”• “Creating P-Code Files”• “How MATLAB Passes Function Arguments”• “Function Workspaces”Function Name ResolutionWhen MATLAB comes upon a new name, it resolves it into a specific functionby following these steps:1 Checks to see if the name is a variable.2 Checks to see if the name is a subfunction, a MATLAB function that residesin the same M-file as the calling function.
Subfunctions are discussed in thesection, “Subfunctions” on page 17-43.3 Checks to see if the name is a private function, a MATLAB function thatresides in a private directory, a directory accessible only to M-files in thedirectory immediately above it. Private directories are discussed in thesection, “Private Functions” on page 17-45.4 Checks to see if the name is a function on the MATLAB search path.MATLAB uses the first file it encounters with the specified name.If you duplicate function names, MATLAB executes the one found first usingthe above rules. It is also possible to overload function names. This usesadditional dispatching rules and is discussed in the section, “How MATLABDetermines Which Method to Call” on page 22-67.17-12FunctionsWhat Happens When You Call a FunctionWhen you call a function M-file from either the command line or from withinanother M-file, MATLAB parses the function into pseudocode and stores it inmemory.
This prevents MATLAB from having to reparse a function each timeyou call it during a session. The pseudocode remains in memory until you clearit using the clear function, or until you quit MATLAB.You can use clear in any of the following ways to remove functions from theMATLAB workspace.SyntaxDescriptionclear function_nameRemove specified function from workspaceclear functionsRemove all compiled M-functionsclear allRemove all variables and functionsCreating P-Code FilesYou can save a preparsed version of a function or script, called P-code files, forlater MATLAB sessions using the pcode function.
For example,pcode averageparses average.m and saves the resulting pseudocode to the file namedaverage.p. This saves MATLAB from reparsing average.m the first time youcall it in each session.MATLAB is very fast at parsing so the pcode function rarely makes much of aspeed difference.One situation where pcode does provide a speed benefit is for large GUIapplications.
















