I have a function that takes optional arguments as name/value pairs.
function example(varargin)
% Lots of set up stuff
vargs = varargin;
nargs = length(vargs);
names = vargs(1:2:nargs);
values = vargs(2:2:nargs);
validnames = {'foo', 'bar', 'baz'};
for name = names
validatestring(name{:}, validnames);
end
% Do something ...
foo = strmatch('foo', names);
disp(values(foo))
end
example('foo', 1:10, 'bar', 'qwerty')
It seems that there is a lot of effort involved in extracting the appropriate values (and it still isn't particularly robust again badly specified inputs). Is there a better way of handling these name/value pairs? Are there any helper functions that come with MATLAB to assist?
Here's the solution I'm trialling, based upon Jonas' idea.
Read Loren's informative post on this issue. Don't forget to read the comments section... - You will see that there are quite a few different approaches to this topic. They all work, so selecting a prefered method is really a matter of personal taste and maintainability.
I'm a bigger fan of home-grown boiler plate code like this:
This way I can simulate the 'option', value pair that's nearly identical to how most Matlab functions take their arguments.
Hope that helps,
Will
I ended up writing this today, and then found these mentions. Mine uses struct's and struct 'overlays' for options. It essentially mirrors the functionality of setstructfields() except that new parameters can not be added. It also has an option for recursing, whereas setstructfields() does it automatically. It can take in a cell array of paired values by calling struct(args{:}).
I'd say that using the naming convention 'defaults' and 'new' would probably be better :P
Since ages I am using
process_options.m
. It is stable, easy to use and has been included in various matlab frameworks. Don't know anything about performance though – might be that there are faster implementations.Feature I like most with
process_options
is theunused_args
return value, that can be used to split input args in groups of args for, e.g., subprocesses.And you can easily define default values.
Most importantly: using
process_options.m
usually results in readable and maintainable option definitions.Example code:
This does of course not check for correct assignments, but it's simple and any useless variable will be ignored anyway. It also only works for numerics, strings and arrays, but not for matrices, cells or structures.