Saturday, November 07, 2009

Useful Matlab / Octave script to make default function arguments easier


The lack of an easy way of making default function arguments in MATLAB (I have R2007a) was annoying me for a long time. Octave (current version 3.2), which is an open source equivalent of MATLAB is much better in terms of handling default function arguments.

What I mean, can be explained best by simple example.

So, lets define a very simple m file, called testDefaultArguments.m with the following function.
function testDefaultArguments(a=1,b=2)
fprintf(1,'a=%d, b=%d\n',a,b);
We see that we have a function called testDefaultArguments with two arguments a and b, and we assign default values to them, i.e. 1 and 2, respectively. Such syntax seems to be helpful, because you can execute testDefaultArguments function as follows:octave-3.2.3:40> testDefaultArguments()
a=1, b=2
octave-3.2.3:41> testDefaultArguments(3)
a=3, b=2
octave-3.2.3:42> testDefaultArguments(a=43)
a=43, b=2
octave-3.2.3:43> testDefaultArguments(a=43,5)
a=43, b=5
octave-3.2.3:44> testDefaultArguments(a=43,b=55)
a=43, b=55
So everything seems good, but what if you want to assign only value to b, and not to a?Lets tryoctave-3.2.3:47> testDefaultArguments(b=55)
a=55, b=2 %!!! a is 55 and not b !!! This is strange
So, this is not only strange, but can easily leads to bugs in one's code.

So this was Octave. What about MATLAB? The anwser is: Error! The function testDefaultArguments can't be executed in Matlab (at least in R2007a and R2008a) due to syntax errors!

So, to help myself with making default function arguments in both MATLAB and Octave I made getfunargs.m script, which makes working with default function arguments little easier (To be honest, this function is a modification of getargs.m script). I'm not going to explain how it works, instead I'm just going to show how it can be used.

Lets define function called testDefaultArguments2 which uses getfunargs:function testDefaultArguments2(varargin)

defaults = struct(...
'a',1,...
'b',2 ...
);

args = getfunargs(defaults, varargin);

fprintf(1,'a=%d, b=%d\n',args.a,args.b);
Now, the testDefaultArguments2 can be executed both in MATLAB and Octave as follows:octave-3.2.3:52> testDefaultArguments2()
a=1, b=2
octave-3.2.3:53> testDefaultArguments2('a',3)
a=3, b=2
octave-3.2.3:54> testDefaultArguments2('b',5)
a=1, b=5
octave-3.2.3:55> testDefaultArguments2('b',5,'a',2)
a=2, b=5
It can bee seen now, that the default arguments work as expected.