MATLAB Answers

Variable changes value after using load

14 views (last 30 days)
Elías Heimisson
Elías Heimisson on 13 Jun 2014
Commented: dpb on 13 Jun 2014
I've been writing a script that runs a function with numerous subfunctions and I've been careful to not use global variables. At one point in the main function a few matrices saved as .mat are loaded if they do not exists in the workspace. The strange thing is that a variable of mine: maxnumsource = 2; That is one of the input parameters in that defines in the script that runs the main function changes value and is somehow redefined as maxnumsource = 1; after doing the load command. I wrote out the values of the variable right before and after the load and somehow it's redefined! Now the even stranger thing is that when I changed the name to maxnumsources with the added 's' this didn't happen anymore. So I 'fixed' the problem but I would like to know why this happens so I can avoid this in the future. And before anyone asks: No the loaded variables were not named maxnumsource.


Show 1 older comment
dpb on 13 Jun 2014
...loaded variables were not named maxnumsource.
The crystal ball says it was by accident during debugging or testing by a save that inadvertently included the variable.
whos -file 'yourmatfile'
and see. You could check for how many and which ones were accidentally contaminated automagically by
for i=1:length(d)
if ~isempty(s)
for j=1:length(s)
disp([d(i).name 'contains ' s(j).name]
I'm betting you'll find at least one case...
Elías Heimisson
Elías Heimisson on 13 Jun 2014
My bad, this was actually a very silly mistake. When I saved the matrix which I then load I forgot to include the variable name. So all variables that were in the workspace when I calculated this matrix were saved including maxnumsource. This matrix was calculated in a seperate script so I was looking for the bug in the wrong place.
dpb on 13 Jun 2014
Told ya'... :)
Easy mistake to make; no problem...

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 13 Jun 2014
Always accept the results of load() into a structure so that you don't poof variables into existence and cause problems like you did.
storedStructure = load(fullFileName);
var1 = storedStructure.var1;
var2 = storedStructure.var2;
For example if there was a var3 in there, it's not going to blast over any var3 that I already have because I didn't explicitly allow it.

  1 Comment

dpb on 13 Jun 2014
Most excellent point, IA! +1

Sign in to comment.

More Answers (0)

Sign in to answer this question.