Programming |
M-files can contain code for more than one function. Additional functions within the file are called subfunctions, and these are only visible to the primary function or to other subfunctions in the same file.
Each subfunction begins with its own function definition line. The functions immediately follow each other. The various subfunctions can occur in any order, as long as the primary function appears first:
function [avg, med] = newstats(u) % Primary function % NEWSTATS Find mean and median with internal functions. n = length(u); avg = mean(u, n); med = median(u, n); function a = mean(v, n) % Subfunction % Calculate average. a = sum(v)/n; function m = median(v, n) % Subfunction % Calculate median. w = sort(v); if rem(n, 2) == 1 m = w((n+1) / 2); else m = (w(n/2) + w(n/2+1)) / 2; end
The subfunctions mean
and median
calculate the average and median of the input list. The primary function newstats
determines the length of the list and calls the subfunctions, passing to them the list length n
.
Subfunctions cannot access variables used by other subfunctions, even within the same M-file, or variables used by the primary function of that M-file, unless you declare them as global within the pertinent functions, or pass them as arguments.
Calling Subfunctions
When you call a function from within an M-file, MATLAB first checks the file to see if the function is a subfunction. It then checks for a private function (described in the following section) with that name, and then for a standard M-file or built-in function on your search path. Because it checks for a subfunction first, you can override existing M-files using subfunctions with the same name.
Accessing Help for a Subfunction
You can write help for subfunctions using the same rules that apply to primary functions. To display the help for a subfunction, precede the subfunction name with the name of the M-file that contains the subfunction (minus file extension) and a >
character.
For example, to get help on subfunction mysubfun
in file myfun.m
, type
Examples of Nested Functions | Private Functions |
© 1994-2005 The MathWorks, Inc.