Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out which variable is triggering Matlab warning about global variables

I'm working with Matlab R2018a on Linux. I am getting the warning message:

"Warning: The value of local variables may have been changed to match the globals. Future versions of MATLAB will require that you declare a variable to be global before you use that variable."

The warning is accompanied by file name and line number, but there are several variables on that line, so I wonder to which one the message refers.

Is there a way to find out which variable the warning is complaining about?

Is there a way to turn the warning into an error? Maybe that would make it easier to fix the problem rather than just tolerating it.

like image 979
Robert Dodier Avatar asked Jan 28 '23 20:01

Robert Dodier


1 Answers

This error is triggered on a line where you declare a variable to be global, but that variable is already in use as a local variable:

baz = 3;
% ... much later...
global foo bar baz

To find out which of these variables was already defined, you can set a breakpoint at the global line, and see which variables exist at that moment.

You can also add a who command just before this line, and observe the console output of your program just before the warning is generated.

Once you found the variable name that is triggering the error, you can rename the local variable with that name, leaving the global variable unchanged.

A shoutout to @flawr and @SardarUsama who helped figure out the meaning of this warning message over on the MATLAB chat.


Below is part of the original answer, which shows a way to determine if a variables is global.


As @Durkee suggested, whos global will list global variables. You can use this programatically to test for "globalness":

~isempty(whos('global','varname'))

(note that isglobal used to be a function in MATLAB a long time ago, but has since been removed).

like image 174
Cris Luengo Avatar answered Apr 09 '23 17:04

Cris Luengo