MATLAB: Once more… Avoid global variable!

data sharingdefaultfaqglobal variablesinput argumentsvariable

Hello together,
I'm writing many function which i often use during a matlab session. To make them a little more compfortalbe to use i'd like to use a data structure in some way, where i can store some preference data. The preference data is for example some input arguments the functions have in common. But because the values of these input arguments change from time to time, so i can not set it as default values in the function.
Global variables look perfect for this task, but i've read a lot of comments that global variables are bad and i'd rather avoid using them. But what other ways are there, to store my preference data and use it in different functions.
thank you for your help.
Rafael

Best Answer

You can create a "global function" to store static parameters:
function G = theGlobalData()
G.pi = 3.14;
G.imag = 1i;
G.PIN = 5553;
end
You might add some input arguments also or store G persistently:
function G = theGlobalData(Name, Value)
persistent G_
if isempty(G_)
G_.pi = 3.14;
G_.imag = 1i;
G_.PIN = 5553;
end
if nargin > 0
G_.(Name) = Value;
end
G = G_;
end
This shares the problem of global variables, that e.g. running multiple instances of your program can cause collisions of the values. But at least you can debug each access of this function. Setting a breakpoint in it allows to track all events.
I'd prefer sharing the struct inside the code by using input and output arguments. Passing an additional argument is neither clumsy nor slow and there is no danger of interferences with other instances of your code or other software.
These ideas are "create a parameters function" and "pass a struct" of Stephen's answer.