There are various ways to handle variable input arguments (varargin) in Matlab. I present the standard getOptions method I developed that is simple, flexible, and allows for more readable code.
Update getOptions now has a repository: https://github.com/bahanonu/getOptions or https://www.mathworks.com/matlabcentral/fileexchange/75464-getoptions.
Matlab doesn't adopt R, python, or various other language's syntax for passing optional arguments, namely, you can't specify the name-value pair in the list of inputs to the function. While this might initially seem to be a weakness, it can allow for cleaner, more flexible code with the right planning.
The main goal is to have a set of inputs that have default states within the function—often magic numbers or other hard-coded constants are placed here so they are easily edited and their impact understood. One way to deal with Matlab's method of passing optional parameters is to just pass an options structure as the sole name-value pair, with fieldnames containing the options used by the function.
However, this is not very flexible and the feature cannot be easily enhanced across all functions in a project. Further, it is not the most readable or consistent code and the same sequence of actions is repeated in the actual source code instead of dynamically/filter grabbing options set in the input. Another method is to then loop over name-value pair inputs.
This method isn't necessarily better, but solves the problem in a slightly different manner that in essence keeps the same problems: it still relies on a hard-coded enumeration of all acceptable variable input parameters. As more options are added, this can grow to consume a good chunk of the introductory code in a function and is not super friendly to someone skimming the code.
An alternative method is presented below (see getOptions.m). The idea is to take advantage of the repeated nature of how variable input arguments are dealt with along with dynamic filtering to ensure that the user cannot input invalid parameters. The solution is to always put all available options into a structure, called options, at the beginning of each function. This structure contains fieldnames that a user can input via classic name-value pairs, e.g. foobar('electionYear', 1992), or via a special options name-value pair wherein an options structure is created with fieldnames to be modified (see exampleScript.m below). In either case, a single function then deals with looping over all variable inputs and replaces the default values that match a valid fieldname. This is done dynamically, which means that if additional options are added, no new code is needed to help filter and add the new options name-value pairs to the functions settings.
While this introduces some restrictions on how a function responds to a given input, e.g. you cannot immediately call a new function based on user input before parsing all variable arguments (perhaps for the better), it forces a consistent format to how options are dealt with and allows for added functionality to be implemented across all functions in a project quickly.
For example, the special options name-value input argument was added later and instantly allowed me to reduce super-long code-lines with a ton of name-value pairs to several lines each with a single fieldname and input value, allowing for easier readability and (in the future) more dynamic parameter passing. This would have been much harder to implement across every script in my current project using the two previous methods.
More small code snippets to come in the future, for now, enjoy the example below!
- % pass option via a name-value pair
- [output] = exampleFxn('foo',1,'bar','Call me Ishmael');
- % or pass option via options structure
- inputOptions.foo = 1;
- inputOptions.bar = 'Call me Ishmael';
- [output] = exampleFxn('options',inputOptions);
- % example function with outline for necessary components
- % biafra ahanonu
- % updated: 2014.02.17
- %========================
- options.foo = 0;
- options.bar = 'hello world';
- % get options
- % display(options)
- % unpack options into current workspace
- % fn=fieldnames(options);
- % for i=1:length(fn)
- % eval([fn{i} '=options.' fn{i} ';']);
- % end
- %========================
- try
- if options.foobar==1
- % do something
- else
- % do something else
- end
- catch err
- end
- % gets default options for a function, replaces with inputArgs inputs if they are present
- % biafra ahanonu
- % 2014.02.17 [22:21:49]
- %
- % inputs
- % options - structure with options as fieldnames
- % inputArgs - varargin containing name-value pairs passed from parent function.
- % list of valid options to accept, simple way to deal with illegal user input
- % loop over each input name-value pair, check whether name is valid and overwrite fieldname in options structure.
- if ischar(val)
- % allow input of an options structure that overwrites existing fieldnames with its own, for increased flexibility
- [options] = mirrorRightStruct(inputOptions,options);
- end
- else
- continue;
- end
- end
- function [pullStruct] = mirrorRightStruct(pushStruct,pullStruct)
- % overwrites fields in pullStruct with those in pushStruct, other pullStruct fields rename intact
- % more generally, copies fields in pushStruct into pullStruct, if there is an overlap in field names, pushStruct overwrites.
- iName = pushNames{name};
- pullStruct.(iName) = pushStruct.(iName);
- end