Programming and Data Types

Subfunctions

Function M-files can contain code for more than one function. The first function in the file is the primary function, the function invoked with the M-file name. Additional functions within the file are subfunctions that are only visible to the primary function or 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`. Functions within the same M-file cannot access the same variables unless you declare them as global within the pertinent functions, or pass them as arguments. In addition, the help facility can only access the primary function in an M-file.

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 on your search path. Because it checks for a subfunction first, you can supersede existing M-files using subfunctions with the same name, for example, `mean` in the above code. Function names must be unique within an M-file, however.

 Passing Variable Numbers of Arguments Private Functions