Depending on the structure of your algorithm, there's likely to be a third option, which is to use nested functions. A nested function has its own workspace (variable scope), but also has access to variables in the workspaces of functions within which it is nested - without them being properly global.
Whenever I've implemented recursive functions in MATLAB I've found this to be an approach which typically makes the code quite clean.
Here's a simple arithmetic example:
function z = times1(x,y)
if y == 0
z = 0;
else
z = plusy(times1(x, y-1));
end
function z = plusy(x)
z = x+y;
end
end
You can see that the variable y
is used within the nested function plusy
even though it's not an input argument, but in the workspace of the parent function; nevertheless it's not a global. (Note that in recent versions of MATLAB, y
will be coloured light blue in the editor to emphasize this shared scope).
As to which approach is going to be fastest and use least memory, that's likely to depend very much on the details of your particular algorithm - how much copying of data there is, the depth of the recursion etc. I would think you'd need to experiment and take some timings, either with tic
and toc
, or even better with Steve Eddins' timeit function from the MATLAB Central File Exchange.