Opt args
From QETLAB
opt_args | |
Handles optional input arguments for functions | |
Other toolboxes required | none |
---|---|
Function category | Helper functions |
This is a helper function that only exists to aid other functions in QETLAB. If you are an end-user of QETLAB, you likely will never have a reason to use this function. |
opt_args is a function that provides a simple way of handling optional arguments within other functions. It reads in a cell of default values of variables and replaces them by optional argument values if those values were provided by the end-user. This reduces a check for optional arguments from what is often 8 or 9 lines of code down to 1 line of code, and also makes code easier to read. End-users of QETLAB have no reason to use this function.
Syntax
- VARARGOUT = opt_args(DEF_ARGS,EXTRA_ARG1,EXTRA_ARG2,...)
Argument descriptions
- DEF_ARGS: A cell containing default argument values. These same values will be output by opt_args unless they are overwritten by one of the optional arguments.
- EXTRA_ARGn (optional): If provided, the n-th optional argument to this function will be its n-th output argument (in place of DEF_ARGS{n}).
Examples
Please see the source code of functions such as PermuteSystems to see examples of this function in use.
Source code
Click on "expand" to the right to view the MATLAB source code for this function.
%% OPT_ARGS Handles optional input arguments for functions
% This function has one required argument: DEF_ARGS, and an arbitrary
% number of additional optional arguments
%
% VARARGOUT = opt_args(DEF_ARGS,EXTRA_ARG1,EXTRA_ARG2,...) provides the
% values EXTRA_ARG1, EXTRA_ARG2, ..., with the understanding that if a
% particular EXTRA_ARGn is not provided as input, then DEF_ARGS(n) is
% returned in its place. This is a helper function that is only used to
% clean up and simplify code within other functions.
%
% URL: http://www.qetlab.com/opt_args
% requires: nothing
% author: Nathaniel Johnston (nathaniel@njohnston.ca)
% package: QETLAB
% last updated: November 2, 2012
function varargout = opt_args(def_args,varargin)
% verify optional arguments
max_opt_args = length(def_args);
num_opt_args = length(varargin);
if num_opt_args > max_opt_args
ST = dbstack(1);
error(strcat(ST.name,':TooManyArguments'),'Received %d optional arguments, but expected no more than %d.',num_opt_args,max_opt_args);
end
% return argument values
varargout = def_args;
varargout(1:num_opt_args) = varargin;