MATLAB - Global Variables
30 Jun 2009 Zane Montgomery 9 comments 4,230 views
How do global variables differ from regular (local) variables?
Each function in MATLAB contains a set of variables specific to that function. Even in the same .m file, you don’t have (direct) access to variables created in other functions within the file. Global variables give you the ability to create/change a variable in one function and have that updated variable accessible elsewhere. This post will discuss two methods for handling (no pun intended) global variables, one of which is perfectly integrated into Graphical User Interfaces (GUIs).
METHOD 1: global VARIABLE
The first (non-GUI) way to create a global variable is to use the function ‘global’. Create the global variables X, Y, and Z with the command:
global X Y Z
The ‘global’ function needs to be called in each separate function (usually in the beginning) where the variables will be called. Stylistically, the variable names are usually longer names and all in CAPS to indicate global variables within the functions. The documented example in the MATLAB helps shows this pretty well:
function tic global TICTOC %define/incorporate global variable at start of function TICTOC = clock; function t = toc global TICTOC %accesses variable TICTOC (or creates it if TICTOC is undefined) if nargout < 1 elapsed_time = etime(clock, TICTOC) else t = etime(clock, TICTOC); end
Many hard-core coders prefer to avoid using ‘global’ except for constants. The reason behind this is because it’s generally considered poor form to lock up a variable name (See Steve L’s comment below for another reason!). While this won’t matter for smaller programs and functions, when the files get to be many hundreds (or thousands or millions) of lines long, it can be very difficult to keep track of all of the global variables and to remember to call all the necessary variables at the start of each function. The great thing about GUIs is that they already have a built-in global structure to deal with all of your global variables: the handles. The handles structure is an input (and therefore accessible) to every function in the GUI, making it perfectly capable doing everything the ‘global’ command can. In fact, you shouldn’t ever have to use ‘global’ command when designing a GUI because the handles structure does the job so well. GUIs and ‘global’ don’t mix kids!
METHOD 2: handles.variable
As you may have seen from many of the blinkdagger GUI tutorials, the handles structure is an extremely useful method to manipulate GUI boxes/buttons/tools. But the tool data are all just stored variables that can be accessed anywhere within the GUI (aka global variables!). Since we don’t need to edit any ‘property’ of the handles structure (e.g. handles.static_text, ‘String’), we don’t need to use the ‘get’/’set’ commands. Creating the global variable is as easy as saying:
handles.x = 42;
%And of course, don't forget to update your handles structure:
guidata(hObject, handles);
handles.x is now an independent variable and note that it has no relation to the local variable x.
x = 43;
is a completely valid command in the same function that would not overwrite your global variable ‘handles.x’.
Remember, these variables can range from constants (e.g. 12) to strings (e.g. ‘Hello World’) to structures, cells, and arrays of constants/strings.
Hopefully you can see the usefullness of global variables and will use them (properly!) in your coding adventures.
9 Responses to “MATLAB - Global Variables”
Leave a Reply
Include MATLAB code in your comment by doing the following:
<pre lang="MATLAB">
%insert code here
</pre>


When I started using GUIs a couple of years ago I couldn’t get this right, so ended up storing all my global variables via setappdata(gcbf, ’string’, data). I’ve never had a problem with this, although it is more cumbersome than the handles method you describe here.
I think I’ll use your method in future.
Zane,
In the first method you said “Many hard-core coders prefer to avoid using ‘global’ except for constants. The reason behind this is because it’s generally considered poor form to lock up a variable name.” That’s one reason to avoid using global variables, but a much stronger reason to avoid using global variables is that it can lead to bugs that are very difficult and time consuming to locate, particularly in the context of a GUI.
Suppose I write a function that uses a global variable x.
In isolation, this function works perfectly fine. I set the value of the global variable x and then call myglobalsquare, and I get back the value x^2.
Now I incorporate this function into a GUI. I set it as the callback for one of my GUI’s uicontrols and have another uicontrol’s callback set the value of the global variable x.
I test it and it works, and I go on finishing up the GUI. But suddenly, when I introduce a new object into the GUI and set up its callback, my “Square” button no longer works! What’s going on? I haven’t made any changes to the Square button in hours!
The problem, I find out after spending a LOT of time looking at myglobalsquare and the callback that sets the global variable x, is that the callback for the new object I introduced in the GUI _also_ uses the global variable x. Because of that callback function’s manipulation of the global variable, the myglobalsquare function no longer works the way I expect it to.
If you think of a function workspace as a house, with the input arguments coming in the front door and the output arguments leaving by the back door, a global variable is an open window that anyone can crawl through and move your furniture around, potentially without you realizing it until you invite a very important guest (the data for the real problem you’re trying to solve, not the data you’ve used to test the function) for a visit.
On a side note, I suppose that would make a nested function an apartment in an apartment complex, where the landlord has the right to come in and move stuff around in certain circumstances [mainly maintenance or emergency situations] and the resident doesn’t have the right to do certain things [like paint the walls.]
I love the analogy. Thanks for the tip Steve!
ARGHH! Globals make me crazy…
The handles structure is not global. It is passed around to all the callbacks in a GUI by default, but it is not global.
I know this is partially a religious issue, but I see way too many people abusing true global variables because they do not understand scoping of variables and then they end up in a real mess later.
Please do not use global variables unless you can explain to your teddy bear (http://sjbdeveloper.blogspot.com/2006/03/teddy-bear-code-reviews.html) why you really need them. My bet is you would be better off without them. See below for alternatives.
On to my next religious issue: the handles structure is for handles. It just feels untidy to put data in a structure specifically labeled for handles.
I see people putting just tons of data into the handles structure and it becomes a real mess. Is it going to cause as many problems as globals? Not likely. However, I highly recommend the use of GETAPPDATA and SETAPPDATA as shown in this video:
http://blogs.mathworks.com/videos/2005/10/03/guide-video-part-two/
To me, this is cleaner.
Loren is a fan of nested functions
http://blogs.mathworks.com/loren/2008/01/16/nested-functions-and-variable-scope/
Please consider the alternative before using unneeded globals. Globals are often the cause of really tricky errors. Globals are just quicker, easier, more seductive.
Use nested functions or appdata, not as clumsy or random as a global. An elegant weapon, for a more civilized age.
-Doug
Is it ok to use the userdata from the root?
like
ud=get(0,’userdata’);
ud.x=42;
set(0,’userdata’,ud);
I’m writing GUIs that contain some pretty large data arrays, and don’t want these to be unnecessary duplicated, using up RAM. I’m currently using global variables.
Whilst I appreciate the elegance of Method 2, would switching to this effectively double my memory usage (with one copy of the data in the GUI’s handles structure, and the other in the local handles copy)?
Если бы поисковики понимали суть статей, то думаю они бы внесли вашу в поиск, а не то что некоторые на просторах интернета.
Hi all
I apologize in advance because I don’t have a clue how start a new post…
I need a script which does the following.:
I have the following directory structures
C:/Big/ecm/sDDP/new/level1/level1_1/level1_1_1/*.ext
C:/Big/ecm/sDDP/new/level1/level1_1/level1_1_2/*.ext
C:/Big/ecm/sDDP/new/level1/level1_1/level1_1_3/*.ext
.
.
.
C:/Big/ecm/sDDP/new/level2/level2_1/level2_1_1/*.ext
C:/Big/ecm/sDDP/new/level2/level2_1/level2_1_2/*.ext
C:/Big/ecm/sDDP/new/level2/level2_1/level2_1_3/*.ext
.
.
.
etc.
I want to go through the folders levelx_y_z(where x, y, z stands for 1_1_1, 1_1_2 etc.)
to get the files *.ext. I don’t want to select these files manually with ‘uigetfile’, because it’s
very time consuming. Could anyone help me please. I tried something with ‘fullfile(path, ‘*.ext’)’ but then I still have
to specify each path.
P.s. The folders levelx/levelx_y/level/x_y_z are named otherwise actually. I just wanted to
illustrate the structure
%insert code here