Programming |
Function Arguments
This section covers the following topics:
Getting the Input and Output Arguments
Use nargin
and nargout
to determine the number of input and output arguments in a particular function call. Use nargchk
and nargoutchk
to verify that your function is called with the required number of input and output arguments.
function [x, y] = myplot(a, b, c, d) disp(nargchk(2, 4, nargin)) % Allow 2 to 4 inputs disp(nargoutchk(0, 2, nargout)) % Allow 0 to 2 outputs x = plot(a, b); if nargin == 4 y = myfun(c, d); end
Variable Numbers of Arguments
You can call functions with fewer input and output arguments than you have specified in the function definition, but not more. If you want to call a function with a variable number of arguments, use the varargin
and varargout
function parameters in the function definition.
This function returns the size vector and, optionally, individual dimensions:
function [s, varargout] = mysize(x) nout = max(nargout, 1) - 1; s = size(x); for k = 1:nout varargout(k) = {s(k)}; end
String or Numeric Arguments
If you are passing only string arguments into a function, you can use MATLAB command syntax. All arguments entered in command syntax are interpreted as strings.
When passing numeric arguments, it is best to use function syntax unless you want the number passed as a string. The right-hand example below passes the number 75
as the string, '75'
.
For more information: See Passing Arguments in the MATLAB Programming documentation.
Passing Arguments in a Structure
Instead of requiring an additional argument for every value you want to pass in a function call, you can package them in a MATLAB structure and pass the structure. Make each input you want to pass a separate field in the structure argument, using descriptive names for the fields.
Structures allow you to change the number, contents, or order of the arguments without having to modify the function. They can also be useful when you have a number of functions that need similar information.
Passing Arguments in a Cell Array
You can also group arguments into cell arrays. The disadvantage over structures is that you don't have fieldnames to describe each variable. The advantage is that cell arrays are referenced by index, allowing you to loop through a cell array and access each argument passed in or out of the function.
M-File Functions | Program Development |
© 1994-2005 The MathWorks, Inc.