Using global variables is a bad idea in general. They impede the debugging and the increase the level of complexity. You find many corresponding discussions here in the forum, but this problem concens other programming languages also. Ask an internet search engine for details.
But of course it is possible:
- Define the global variables in each function, which needs to access them:
function y = myComputations(x)
global gParameter
y = gParameter * x;
end
- This is done inside the callbacks also:
function Button1_Callback(hObject, EventData, handles)
global gParameter
gParameter = 1;
end
function Button2_Callback(hObject, EventData, handles)
global gParameter
gParameter = 2;
end
- If you need the variable in so base workspace, define them as global here also.
If you need the variable in the base workspace only, e.g. as input for a Simulink method, do not define it as global but using:
function Button1_Callback(hObject, EventData, handles)
assignin('base', 'gParameter' 1);
end
This is not as evil as global variables, but you cannot trace the source of the current value of these variables reliably also.
If 'global' means, that the variable needs to be shared between callbacks of a figure only, use either set/getappdata, guidata or the 'UserData' of the corrsponding GUI element. This allows e.g. to run two instances of the same GUI without conflicts. Please ask, if you need further explanations for this.