Save global variables in Matlab
In Matlab, when declaring a variable as global and saving it using the save () command, the variable is also global after loading the .mat file into a new session. The following code shows this behavior:
At the beginning, I have no variables:
>> who
>> who global
Then I create a global variable and save it:
>> global settings
>> settings.test = 1;
>> who
Your variables are:
settings
>> who global
Your variables are:
settings
>> save('test.mat','settings');
After that, I clear the workspace and globals (or start a new Matlab session)
>> clear
>> clearvars -global
>> who
>> who global
When I load the .mat file, the variable is marked as global again, even if I don't specify it now.
>> load test.mat
>> who
Your variables are:
settings
>> who global
Your variables are:
settings
>> clear
>> who
>> who global
Your variables are:
settings
Is there a way to prevent this behavior?
It seems to me that the "global" flag is stored with a variable. Is this really helpful? Suppose we sent me a mat data file where the variables are declared global. Even when loading this file in a function, it will propagate data in my full session. For me this makes the Matlab code very vulnerable.
Thanks in advance.
source to share
As Dan pointed out in the comments, loading a math file containing a global variable into a struct will strip the global attribute.
foo = load('settings.mat');
To fix a global issue with minimal impact on the rest of the code and what the settings.mat file generates and uses, you could extract the field you want:
foo = load('settings.mat');
settings = foo.settings;
This both removes the global attribute and declares where the parameter variable comes from. (Which really helps when doing the inevitable code archeology later on).
source to share