3
votes

In Matlab when declaring a variable as global and save it using the save() command, the variable is also global after loading the .mat-file in a new session. Following code shows this behavior:

In the beginning, I have no variables:

>> who
>> who global

Then, I create the 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 global variables (or start a new Matlab session)

>> clear
>> clearvars -global
>> who
>> who global

When I then load the .mat file, the variable is again marked as global, even when 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 any way to prevent this behavior?

It seems to me, the "global" flag is saved with the variable. Is this really useful? Suppose one sends me a mat-file with data, where variables are declared as global. Even when loading this file in function, it will spread the data in my complete session. For me this makes Matlab code very vulnerable.

Thank you in advance.

1
What about settings = load test.mat? Is that still global? - Dan
No, in this case, settings would not be global, but it results in: settings.settings.test. - Nemesis
This is considered much better practice though as it makes it much easier to see where loaded variables come from... blogs.mathworks.com/loren/2012/01/13/… you're doing numbers 7 and 9 in that list of bad practice :/ - Dan
Also you can avoid the struct output if you save it as an ASCII file instead of a MAT file (see save and load docs) - Dan
Thanks for the link. I was a bit reluctant about using ... = load, since it would require changes in code that I have used over the years. But using something like save('test.mat','-struct','settings') and settings = load('test.mat') would solve the issue here. I was just wondering, why the "global" flag for a variable was also saved in the .mat file. - Nemesis

1 Answers

1
votes

As noted by Dan in the comments, loading a mat file containing a global variable into a structure strips the global attribute.

foo = load('settings.mat'); 

To fix the global problem with minimal impact to the rest of the code, both that which generates and which uses the settings.mat file, you could then extract the desired field:

foo = load('settings.mat');
settings = foo.settings;

This both removes the global attribute, and declares where the settings variable comes from. (Which really helps when performing the inevitable code archaeology later on).