3

I am using a recursive function in Matlab where some variable are required at each level, these don't change. Though some do change in functions and also need to be reflected in main program.

I'd like to know which is best:

  • To define variables global in main & function like global in1, in2, out1
  • or pass then as arguments to function like [out1]=functionName(in1,in2)

As my program is complex I'd like to reduce the memory requirement and have fast execution.

Lewis Norton
  • 6,911
  • 1
  • 19
  • 29
prateek
  • 31
  • 3

1 Answers1

3

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.

Sam Roberts
  • 23,951
  • 1
  • 40
  • 64