Opt args

From QETLAB
Jump to: navigation, search
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.

  1. %%  OPT_ARGS    Handles optional input arguments for functions
  2. %   This function has one required argument: DEF_ARGS, and an arbitrary
  3. %   number of additional optional arguments
  4. %
  5. %   VARARGOUT = opt_args(DEF_ARGS,EXTRA_ARG1,EXTRA_ARG2,...) provides the
  6. %   values EXTRA_ARG1, EXTRA_ARG2, ..., with the understanding that if a
  7. %   particular EXTRA_ARGn is not provided as input, then DEF_ARGS(n) is
  8. %   returned in its place. This is a helper function that is only used to
  9. %   clean up and simplify code within other functions.
  10. %
  11. %   URL: http://www.qetlab.com/opt_args
  12.  
  13. %   requires: nothing
  14. %   author: Nathaniel Johnston (nathaniel@njohnston.ca)
  15. %   package: QETLAB
  16. %   last updated: November 2, 2012
  17.  
  18. function varargout = opt_args(def_args,varargin)
  19.  
  20. % verify optional arguments
  21. max_opt_args = length(def_args);
  22. num_opt_args = length(varargin);
  23. if num_opt_args > max_opt_args
  24.     ST = dbstack(1);
  25.     error(strcat(ST.name,':TooManyArguments'),'Received %d optional arguments, but expected no more than %d.',num_opt_args,max_opt_args);
  26. end
  27.  
  28. % return argument values
  29. varargout = def_args;
  30. varargout(1:num_opt_args) = varargin;