Graphics Programs Reference
In-Depth Information
Other Programming Commands
In this section we describe several more advanced programming commands
and techniques.
Subfunctions
In addition to appearing on the first line of a function M-file, the command
function can be used later in the M-file to define an auxiliary function, or
subfunction , which can be used anywhere within the M-file but will not be
accessible directly from the command line. For example, the following M-file
sums the cube roots of a vector x of real numbers:
function y = sumcuberoots(x)
y = sum(cuberoot(x));
% ---- Subfunction starts here.
function z = cuberoot(x)
z = sign(x).*abs(x).ˆ(1/3);
Here the subfunction cuberoot takes the cube root of x element-by-element,
butitcannotbeusedfromthecommandlineunlessplacedinaseparateM-file.
You can only use subfunctions in a function M-file, not in a script M-file. For
examplesoftheuseofsubfunctions,youcanexaminemanyofMATLAB'sbuilt-
in function M-files. For example, type ezplot will display three different
subfunctions.
Commands for Parsing Input and Output
You may have noticed that many MATLAB functions allow you to vary the
type and/or the number of arguments you give as input to the function. You
can use the commands nargin , nargout , varargin , and varargout in your
own M-files to handle variable numbers of input and/or output arguments,
whereas to treat different types of input arguments differently you can use
commands suchas isnumeric and ischar .
When a function M-file is executed, the functions nargin and nargout re-
port respectively the number of input and output arguments that were speci-
fied on the command line. To illustrate the use of nargin , consider the follow-
ing M-file add.m that adds either 2 or 3 inputs:
function s = add(x, y, z)
if nargin < 2
Search WWH ::




Custom Search