How to load a .mat file and make all the variables from that .mat file to be global variables?
52 views (last 30 days)
I loaded the .mat file and use the variables in the rest of the codes. Even though the file is loaded outside the for loop, it shows the variable is not defined during the calculation, moreover, the very same variable is used in even earlier calculation. I think the problem is caused by the parfor, so I would like to set the loaded variables as global to see if the problem can be solved.
The part of the code is
load('SobolParameter3Layer.mat');%input: numLayer numPar N Par Para Parac AllCol numCol totalCol
the code can run without problem for the first for loop, but when it comes to parfor, the "numPar" becomes undefined.
Stephen23 on 14 Nov 2018
Edited: Stephen23 on 14 Nov 2018
Always load any .mat file into an output argument (which is a structure):
S = load(...);
This avoids several issues related to overwriting variables, undefined variables, and calling an unexpected function/class/variable. You should be doing this every time you load a .mat file.
Then within your code you simply access the fields of that structure by using dot notation:
More Answers (1)
Adam Danz on 13 Nov 2018
You don't want to make all the mat variable global. That will open a can of worms. If variables in the mat file are needed in other functions, pass those variables to the function.
Also, name the variables you're loading.
load('SobolParameter3Layer.mat', 'numLayer', 'numPar', 'N', 'Par', 'Para', 'Parac', 'AllCol', 'numCol', 'totalCol');
If you try to load a variable that isn't in the mat file you'll get a warning.
Warning: Variable 'fubar' not found.
If you make these changes and still get an error, please comment including the full copy-pasted error message and what time is producing it.