Global variables in MATLAB GUI?

Alvi Syahrin picture Alvi Syahrin · May 11, 2013 · Viewed 13.8k times · Source

I'm working with MATLAB GUI.

When I'm trying to access the variable which was defined with the push button, it is not defined in the pop up menu. The variables; it should be set 'global', so it is defined in the whole program. And I can use it in any callback.

Do you guys have any idea of how to make the variables 'global'?

Answer

rascob picture rascob · May 11, 2013

Wherever a global variable is going to be accessed in your code (say, different script files, functions etc.), it should be declared as such: global globalVariable;. Eg.:

function myGUI_OpeningFcn(hObject, eventdata, handles, varargin)
    global myGlobalVar;
    myGlobalVar = [...]
    [...]
end

function btnWriteFile_Callback(hObject, eventdata, handles)
    global myGlobalVar;
    if myGlobalVar [...]
    [...]
end

Notice that in both functions the variable is declared as global in order for them to access it.