# Setting Default Values

Brett's Pick this week is SetDefaultValue, by Richie Cotton.

Richie wrote in the File Exchange introduction to his SetDefaultValue submission that "it's so simple that I nearly didn't upload this, but it does make your functions cleaner." In fact, it is extremely simple, but it is also widely useful. Anyone who has ever written a program, function, or algorithm--in MATLAB or in any other language--has likely had to deal with variable initializations umpteen times. Many of us have come up with clever ways of simplifying the process or, as Richie might say, "prettifying" the code.

SetDefaultValue cleverly uses simple evalin and assignin calls to streamline and prettify the process.

For instance, to conditionally set x to 1 and y to 3 as defaults, one might write:

if nargin < 1 || isempty(x)
x = 1;
end

if nargin < 2 || isempty(y)
y = 3;
end

Richie's submission introduction referred to Loren's blog about setting defaults. Loren described the use of a switch/case approach, switching based on the number of input arguments. That is a perfectly reasonable approach, and one that I've used many times.

My personal style usually has me writing something along these lines:

% FUNCTION SYNTAX: foo(reqdArg1,reqdArg2,varargin)

% Defaults
x = 1;y = 2;
if nargin > 2, x = varargin{1};end
if nargin > 3, y = varargin{2};end

With Richie's function, one could replace those lines with these:

SetDefaultValue(1, 'x', 1);
SetDefaultValue(2, 'y', 3);

Sometimes, the simplest functions are the most useful ones!

Anyone else have any clever ways to share for dealing with default values? Share them, or your thoughts on the approaches mentioned here, using the comments box below.

Published with MATLAB® 7.10

|