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;endfunction 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};% functionx=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;endfunction 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