I have an aged code from different authors who use global variables over many years and the following challenge: I imported several (>200) variables from an excel file. They are not inside a function and they are not designated as global. For the function to work, they have to be because there is one function1 which calls a function 2. Function 1 is called once only while function 2 is called >10000 times, so I wish anything global to be inside function 1. How can I easily turn all of them into global variables and pass them to function 2?
example (scheme)
% function1
% global *other variables exist here already*
% this function calls function2 at a certain point further below
L=whos
save L % some variables a b c ... are parameters in function2
% function2
% global *other variables exist here already*
load L % i dont want to load my workspace everytime, I rather wish to just access global variables a b c...
% the problem is that my variables sometimes change name and I want to have
% them all global in an automatic way. Or live with a workaround.
Thank you for your patience and I am ready to take questions!
UPDATE I:
I managed a workaround with which im not entirely happy because it involves manual manipulation in the code. So it is a temporary solution at best.
% lets say you have some workspace variables and you save them under this name, and then load them: load workspacevars.mat;
L=who % gives you those variable's names as string column L=L' % and in a form that makes you able to use it as global (as row)
% unfortunately using global L doesnt work for me. any ideas? % I had to go to L in the workspace, and click and drag the resulting long string into a text editor. % there, I removed the braces {} and the '' because this is how global likes to have their variables: pure.
% finally it looks like this: global var1 var2 var3 ....
The answer is, use structure files instead of globals.
once the struct is created, (c.constant1, c.constant2...), you just give the function in question c. I used to work with workspace a lot, which explains why I save my workspace and load it once (not many times since constants dont change) so this is how it looks for me:
inputs are x and c and they can be freely shared between both the main and the subfunction. If constants should change due to some events in the function, they may be saved with an if conditions inside the subfunction and are reloaded in the next iteration of the code (but this is another issue adressed here: Change a constant in ODE calculations under particular conditions with a flag)