I am confused nobody has pointed out this blog post by Loren, one of Matlab's developers. The approach is based on varargin
and avoids all those endless and painfull if-then-else
or switch
cases with convoluted conditions. When there are a few default values, the effect is dramatic. Here's an example from the linked blog:
function y = somefun2Alt(a,b,varargin)
% Some function that requires 2 inputs and has some optional inputs.
% only want 3 optional inputs at most
numvarargs = length(varargin);
if numvarargs > 3
error('myfuns:somefun2Alt:TooManyInputs', ...
'requires at most 3 optional inputs');
end
% set defaults for optional inputs
optargs = {eps 17 @magic};
% now put these defaults into the valuesToUse cell array,
% and overwrite the ones specified in varargin.
optargs(1:numvarargs) = varargin;
% or ...
% [optargs{1:numvarargs}] = varargin{:};
% Place optional args in memorable variable names
[tol, mynum, func] = optargs{:};
If you still don't get it, then try reading the entire blog post by Loren. I have written a follow up blog post which deals with missing positional default values. I mean that you could write something like:
somefun2Alt(a, b, '', 42)
and still have the default eps
value for the tol
parameter (and @magic
callback for func
of course). Loren's code allows this with a slight but tricky modification.
Finally, just a few advantages of this approach:
if-then-else
approaches, which get longer with each new default value)Trooth be told, there is a disadvantage too. When you type the function in Matlab shell and forget its parameters, you will see an unhelpful varargin
as a hint. To deal with that, you're advised to write a meaningful usage clause.