Users are able to tailor MATLAB by creating
their own functions and scripts of MATLAB commands and functions. Both scripts
and functions are ordinary ASCII text files external to MATLAB.
The name of each file must end in ``.m'' and must be found on MATLAB's
search path. (It is easiest to start MATLAB from the directory containing
your M-files. See also the command path.) By default
while an M-file is executing its statements are not displayed.
This default behavior can be changed using the echo command.
A script may contain any sequence of MATLAB statements, including references to other M-files. It is invoked like any other command without arguments and acts on the variables of the workspace globally. Each command in the file is executed as though you had typed it into MATLAB. Most of the demos provided by MATLAB are simply scripts.
The first line of a function M-file starts with the word function and declares the name of the function and its input and output parameters. All input parameters and variables defined within the file are local to the function. Figure 1 provides a simple example from the MATLAB User's Guide.
Figure 1: A User Defined Function.
If we type this function into a file called mymean.m, then we can call mymean
like any other MATLAB function.
>> mymean(1:99)
ans =
50
The parameter supplied to mymean is passed by value (not reference) to the
local variable x. The variables m,n,y are also local to mymean
and do not exist after it returns. An M-file function does not alter the
value of variables
in the workspace unless explicit global declarations are made.
To explicitly declare a global variable, include the statement
global var-name in any function (and possibly the MATLAB base
workspace) in which the variable is to be accessed globally.
The MATLAB function eval accepts a single string argument, which it interprets as a MATLAB expression or statement. The following example demonstrates how you can use eval to pass one function to second function as an argument and have the second function call the first function within its body.
Suppose the following function is in the M-file goo.m
function val = goo(x) val = x.^2;and the following function is in the M-file foo.m.
function val = foo(fname, a) % calls another function, whose name is passed as a string to % argument fname, with the parameter a val = eval([fname,'(a)']); % ^^^^^^^^^^^ Constructs a string interpreted as an expression % or statement by eval.Using these functions, the following command
ans =
9