function

Purpose

Extensibility and programming.

Description

New functions can be added to MATLAB's vocabulary if they are expressed in terms of other existing functions. The commands and functions that compose the new function are placed in a text file whose name, which must begin with an alphabetic character, defines the name of the new function, with a filename extension of .m appended. A line at the top of the file contains the syntax definition for the new function. The name of a function, as defined in the first line of the .m file, must 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.

When a function is used that MATLAB does not recognize, it searches for a file of the same name on disk. If it is found, the function is compiled into memory for subsequent use.

If echo is enabled, the file is interpreted instead of compiled so that each input line is viewed as it is executed. Use clear to remove the function from memory.

In general, if you input the name of something to MATLAB, for example by typing foo, the MATLAB interpreter:

1. Looks for foo as a variable.
2. Checks for foo as a built-in function.
3. Looks in the current directory for files named foo.mex and foo.m.
4. Looks in the directories specified by MATLAB's search path for files named foo.mex and foo.m.

See Also

echo, nargin, nargout, path, type, what

(c) Copyright 1994 by The MathWorks, Inc.