Graphics Programs Reference
In-Depth Information
error('At least two input arguments are required.')
end
if nargin == 2
s=x+y;
else
s=x+y+z;
end
First the M-file checks to see if fewer than 2 input arguments were given, and
if so it prints an error message and quits. (See the next section for more about
error and related commands.) Since MATLAB automatically checks to see if
there are more arguments than specified on the first line of the M-file, there is
noneedtodosowithintheM-file.IftheM-filereachesthesecond if statement
in the M-file above, we know there are either 2 or 3 input arguments; the if
statement selects the proper course of action in either case. If you type, for
instance, add(4,5) at the command line, then within the M-file, x is set to
4 , y is set to 5 , and z is left undefined; thus it is important to use nargin to
avoid referring to z in cases where it is undefined.
To allow a greater number of possible inputs to add.m , we could add ad-
ditional arguments on the first line of the M-file and add more cases for
nargin . A better way to do this is to use the specially named input argument
varargin :
function s = add(varargin)
s = sum([varargin{:}]);
In this example, all of the input arguments are assigned to the cell array
varargin . The expression varargin { : } returns a comma-separated list of
the input arguments. In the example above, we convert this list to a vector by
enclosing it in square brackets, forming suitable input for sum .
The sample M-files above assume their input arguments are numeric and
will attempt to add them even if they are not. This may be desirable in some
cases; for instance, bothM-files above will correctly add a mixture of numeric
and symbolic inputs. However, if some of the input arguments are strings,
the result will be either an essentially meaningless numerical answer or an
error message that may be difficult to decipher. MATLAB has a number of
test functions that you can use to make an M-file treat different types of input
arguments differently — either to perform different calculations or to produce
a helpful error message if an input is of an unexpected type. For a list of
some of these test functions, look up the commands beginning with is in the
Programming Commands section of the Glossary .
Search WWH ::




Custom Search