# Optional Arguments Using Empty as Placeholder

I recently posted about optional input arguments and how to override default values. Gautam mentioned wanting to allow empty inputs as defaults.

### Function Defaults Using Empty Arrays

With a little more thought, I was able to adapt the last program I showed to incorporate empty values taking on the defaults. This allows the user to override defaults later in the argument list without having to reset all the previous values. Let's see how this works.

type somefun2AltEmptyDefs
function y = somefun2AltEmptyDefs(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};

% skip any new inputs if they are empty
newVals = cellfun(@(x) ~isempty(x), varargin);

% now put these defaults into the valuesToUse cell array,
% and overwrite the ones specified in varargin.
optargs(newVals) = varargin(newVals);
% or ...
% [optargs{1:numvarargs}] = varargin{:};

% Place optional args in memorable variable names
[tol, mynum, func] = optargs{:};


### Compare Functions

I can use the Compare Against tool (from the Tools menu) to compare my new function with my previous one. Here's a screenshot. You can click on it to see a legible version.

### Differences

There are 2 additional lines and one changed line in the new file. After setting up the cell array of defaults, I now check the varargin cell array for empty arguments. There are ones for which I want to retain the default values. So I find the correct indices for them, and only overwrite or add the non-empty values from varargin.

### Any More Thoughts on Defaults?

If you have any more thoughts on default values, please post them here.

Published with MATLAB® 7.8

|