MATLAB: How to efficiently hand a large numbers of constant variables to functions

function handleperformancevariables

Hi,
I'm new to this forum and hope I'm doing this right.
I have a number of functions that require variables that are declared in the main script. I currently know of the following ways to hand these down to the respective functions:
  • Hand them down one by one (see example)
  • Declare variables global
  • "Pack" the variables into a cell struct, hand down the cell struct and "unpack" them in the nested functions
To hand the variables down one by one is working, but I personally think this make my code messy if the number of variables is huge. I currently use globals though I do know that the use of globals in this context is bad practice and has negative effects on the runtime. The cell struct solution is avoiding both "messyness" and the use of globals. But I am not sure if there is an easier way, as I suspect the "unpacking" to use unnecessary computing time. I also tried the use of persistent but don't seem to make the right use of them.
Solution 1
A=rand(1000,1000);
B=A;
C=A;
D=A;
% function

x=function1(A,B,C,D);
function x=function1(A,B,C,D)
y=function2(A,B,C,D);
x=y;
end
function y=function2(A,B,C,D)
a=round(1000*rand);
y=A(a,a)+B(a,a)+C(a,a)+D(a,a);
end
Solution 2
A=rand(1000,1000);
B=A;
C=A;
D=A;
ABCD={A,B,C,D};
% function
x=function1(ABCD);
function x=function1(ABCD)
A=ABCD{1,1};
B=ABCD{1,2};
C=ABCD{1,3};
D=ABCD{1,4};
% use A,B,C,D and dont change them
y=function2(ABCD);
x=y;
end
function y=function2(ABCD)
A=ABCD{1,1};
B=ABCD{1,2};
C=ABCD{1,3};
D=ABCD{1,4};
a=round(1000*rand);
y=A(a,a)+B(a,a)+C(a,a)+D(a,a);
end

Best Answer

Actually, if your function is truly a nested function it has already access to all the variables in the scope of the parent function and you don't have to pass anything. Simply use the variable, e.g.:
function parentfunction
x = 5
nestedfunction
function nestedfunction
%has access to x without doing anything
y = x + 2;
end
end
If it's not a nested function in the true sense, then indeed you need another mechanism. I'd say avoid global at all cost. They work ok for very small programs. Once the program gets bigger it becomes a maintenance nightmare to track who reads / writes these global variable and thus you greatly increase the risk of bugs. Many many people have been bitten by this hence why the practice is discouraged or not even possible in modern languages.
The packing structure is probably the simplest workaround. The more modern workaround is OOP. Put all the functions that need access to these variable together as methods of a class. This usually results in a much cleaner program interface (at the expense of more initial work and a learning curve if you've not done OOP).
Related Question