MATLAB Function Reference | Search  Help Desk |
function | See Also |
You add new functions to MATLAB's vocabulary by expressing them in terms of existing functions. The existing commands and functions that compose the new function reside in a text file called an M-file. M-files can be either scripts or functions. Scripts are simply files containing a sequence of MATLAB statements. Functions make use of their own local variables and accept input arguments. The name of an M-file begins with an alphabetic character, and has a filename extension of .
m
. The M-file name, less its extension, is what MATLAB searches for when you try to use the script or function.
A line at the top of a function M-file contains the syntax definition. The name of a function, as defined in the first line of the M-file, should be the same as the name of the file without the .m
extension. For example, the existence of a file on disk called stat
.m
with
function [mean,
stdev] = stat(x)
n = length(x);
mean = sum(x)/n;
stdev = sqrt(sum((x-mean).^2/n));
defines a new function called stat
that calculates the mean and standard deviation of a vector. The variables within the body of the function are all local variables.
A subfunction,visible only to the other functions in the same file, is created by defining a new function with the function
keyword after the body of the preceding function or subfunction. For example, avg
is a subfunction within the file stat.m
:
function [mean,stdev] = stat(x) n = length(x); mean = avg(x,n); stdev = sqrt(sum((x-avg(x,n)).^2)/n); function mean = avg(x,n) mean = sum(x)/n;Subfunctions are not visible outside the file where they are defined. Functions normally return when the end of the function is reached. Use a
return
statement to force an early return.
When MATLAB does not recognize a function by name, it searches for a file of the same name on disk. If the function is found, MATLAB compiles it into memory for subsequent use. In general, if you input the name of something to MATLAB, the MATLAB interpreter:
.
.eig
, sin
)that was not
overloaded.
.
.
.
Locates any and all occurrences of function in method
directories and on the
path. Order is of no importance.
.
Checks to see if the name is wired to a specific function (2, 3, & 4 above)
.quit
MATLAB. The pcode
command performs the parsing step and stores the result on the disk as a P-file to be loaded later.
nargin
Number of function arguments (input)
nargout
Number of function arguments(output)
pcode
Create preparsed pseudocode file (P-file)
varargin
Pass or return variable numbers of arguments (input)
varargout
Pass or return variable numbers of arguments (output)
what
Directory listing of M-files, MAT-files, and MEX-files