Per the documentation for global
:
To use a global within a callback, declare the global, use it, then clear the global link from the workspace. This avoids declaring the global after it has been referenced. For example,
cbstr = sprintf('%s, %s, %s, %s, %s', ...
'global MY_GLOBAL', ...
'MY_GLOBAL = 100', ...
'disp(MY_GLOBAL)', ...
'MY_GLOBAL = MY_GLOBAL+1', ...
'clear MY_GLOBAL');
uicontrol('style', 'pushbutton', 'CallBack', cbstr, ...
'string', 'count')
That being said, there typically is never a need to use a global
variable. For GUIs built with GUIDE, consider using setappdata
to access your variables across functions.