Loren on the Art of MATLAB

Turn ideas into MATLAB


Loren on the Art of MATLAB has been archived and will not be updated.

Nice Way to Set Function Defaults

Last week, I wrote a post on the switch statement in MATLAB. One theme in the comments was about using switch (or not!) for setting default values for input arguments that users didn't initialize. I realized that there is a nice pattern for setting these values that uses some compact, but readable code.

There is new functionality in R2019B that supercedes these ideas. Please check out the new functionality for argument validation.


Function Defaults

Sometimes I want to write a function that has some required inputs and some optional trailing arguments. If the arguments are specified by their order, and not by parameter-value pairs, there is a nice way to accomplish this take advantage of varargin. Note that neither of these methods checks the validity of the overridden elements.

Suppose my function requires the first 2 inputs, but there are 3 others that the user can choose to set, or allow them to take default values. In this scenario, once they choose to set an optional input, they must set all the optional ones that precede it in the argument list. Here's an example function header.

dbtype somefun2 1
1     function y = somefun2(a,b,opt1,opt2,opt3)

Here's another way I could write this function header, using varargin.

dbtype somefun2Alt 1
1     function y = somefun2Alt(a,b,varargin)

Setting Default Values

To set default values in somefun2, I could use a switch statement or use if-elseif constructs. Here I chose to use a switch statement.

type somefun2
function y = somefun2(a,b,opt1,opt2,opt3)
% Some function with 2 required inputs, 3 optional.

% Check number of inputs.
if nargin > 5
    error('myfuns:somefun2:TooManyInputs', ...
        'requires at most 3 optional inputs');

% Fill in unset optional values.
switch nargin
    case 2
        opt1 = eps;
        opt2 = 17;
        opt3 = @magic;
    case 3
        opt2 = 17;
        opt3 = @magic;
    case 4
        opt3 = @magic;

The code is verbose and, in my opinion, not very pretty. It's also error-prone. If I decide to change a default setting for one value, I have to update each relevant case. What a drag!

Here's a way to set the defaults in one location and then overwrite the ones the user specified.

type somefun2Alt
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');

% 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{:};

First I place the default optional values into a cell array optargs. I then copy the cells from varargin to the correct cells in optargs and I have overridden the defaults. I have only one place where the default values are set, and the code doesn't grow dramatically in length as I add additional optional inputs. Finally, I spread out the cells from varargin into well-named individual variables, if I want to. Since each element in a cell array is its own MATLAB array, and MATLAB has copy-on-write behavior, I am not creating extra copies of these optional inputs (see this post for more information).

Other Methods for Dealing with Optional Inputs

There are other methods for dealing with optional inputs. These include specifying parameter-value pairs. With or without such pairs, you can use inputParser to help set the values you use. You can specify the optional input in a struct, with fields containing the various options, and you can use cell arrays, but then you have to decide how to structure and specify the contents.

Your Techniques for Specifying Optional Values

Do you have a technique for specifying optional values that works well for you? Please share with us here.

Loren Shure Copyright 2009 The MathWorks, Inc.

Published with MATLAB® R2019b

  • print


To leave a comment, please click here to sign in to your MathWorks Account or create a new one.