|MATLAB Function Reference|
You add new functions to the MATLAB 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
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
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:
sin) that was not overloaded.
directories and on the path. Order is of no importance.
At execution, MATLAB:
When you call an M-file function from the command line or from within another M-file, MATLAB parses the function and stores it in memory. The parsed function remains in memory until cleared with the clear command or you
quit MATLAB. The
pcode command performs the parsing step and stores the result on the disk as a P-file to be loaded later.