I recently posted about optional input arguments and how to override default values. Gautam mentioned wanting to allow empty inputs as defaults.
Contents
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.
Get
the MATLAB code
Published with MATLAB® 7.8




The past couple of posts have been really helpful to me for dealing with setting input arguments. I am surprised by how the number of optional arguments is being checked. Is there a reason that you did not use the nargchk function?
Dan-
I could definitely use nargchk but mentally what I am doing is simple enough that I don’t think to. It doesn’t help with setting the defaults either.
–Loren
Hi Loren.
I have been trying to find the optimal way of dealing with optional arguments and default values for several years, but I find myself of not being able to stick with one best approach. I am trying new ways over and over.
I must actually say, that I like the Python way of dealing with optional arguments and default values, i.e. specifying them directly in the function header. It would be nice to have this feature in MATLAB as well:
function foo(reqArg, optArg1=12, optArg2=’whatever’)
Petr
Petr-
I believe R does something similar as well. Can you please put this into our system as an enhancement request here? It would be more meaningful coming directly from a customer. Thanks.
–Loren
Loren
I just posted the feature request as suggested.
I realized that I did not provide the way I currently consider the most suitable for me. I have converged to an approach very similar to the one in Ben’s comments of the previous article, i.e. using key-value pairs, with defaults defined in a structure in the beginning of a function and then overwriting them with the respective fields of parameters structure.
The only difference is that I prefer to allow for key-value pairs given in the same way as in many MATLAB graphics commands (i.e. converting the varargin cell array to structure inside the function), rather then directly expecting a structure as an argument.
Thanks for showing all these possibilities.
Hi Loren,
I’ve been following your blog for several years now and it’s been interesting to see how the format of the website, style-sheets, etc. have changed.
I’ve noticed lately when you use the “type” command to display the text of a function, it prints it in hard to read italics. I’ve found that when I’m reading code, it’s easier to read and understand if it uses the Matlab Editor’s standard syntax highlighting. Is there a way (maybe using CSS) to have your blog posts format anything between “pre” tags the same way the Editor does it?
-Jessee
Hi Jessee-
Unfortunately I don’t know of a way to do that right now. Having syntax-highlighted code is on our wish list too.
–Loren
Hi! I just wanted to tell you that I found both the last two posts and their comments very insightful. Excellent food for thought! :)
The first method is great, however I’m a bit turned off by the fact that the inputs are all lumped into varargin. As I grew accustomed to Matlab, I learned to identify a function’s arguments with a quick glance at the top line.
I was thinking of accepting the inputs as usual, define a struct with the default values, and pass it to a helper function. The helper function accesses the main function’s variables as defined in the struct, and writes the default values if needed. IMHO it could be an excellent compromise :)
function testing() something('testing ', 'it') something() end function z = something(a, b, c) defaults.a = 'hey '; defaults.b = 'you'; defaults.c = '!'; setdefaults(defaults); z = [a b c]; end function setdefaults(defaults) var_names = evalin('caller', 'whos'); default_names = fieldnames(defaults); must_replace = ~ismember(default_names, var_names); for k = find(must_replace) name = default_names(k); assignin('caller', name, defaults.(name)); end endSorry, I was away from a MATLAB console when I wrote that :) Minor corrections to the function:
function setdefaults(defaults) var_names = evalin('caller', 'who'); default_names = fieldnames(defaults); must_replace = ~ismember(default_names, var_names); for k = find(must_replace)' name = default_names{k}; assignin('caller', name, defaults.(name)); end endI’ve been testing it and it’s pretty handy.
Thanks a lot.. I am learning how to use matlab and these are very useful for me.
so wonderful!