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.
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).
http://www.mathworks.com/matlabcentral/fileexchange/18798
http://www.mathworks.com/matlabcentral/fileexchange/18798
http://stackoverflow.com/questions/8148982/global-variables-and-arguments-in-matlab-which-is-fastest