Search code examples
matlabuser-interfacegetsetmatlab-guide

How to use the same variable in different functions in GUI MATLAB


I have a popup menu with the following code. There are two options as C1 and C2. If the user selects C1, I want to set the value as 10 and if the user selcts C2, I want to set the value as 20.

function pop_Callback(hObject, eventdata, handles)

contents = cellstr(get(hobject,'String'));
A = contents{get(hObject,'Value')};
if (strcmp(A,'C1'))
    X = 10;
elseif (strcmp(A,'C2'))
    X = 20;
end
set(handles.pop,X)

I want to use another function with a pushbutton and static text to display the answer, where the output is, Whatever the set value + 12.

function push_Callback(hObject, eventdata, handles)

inX = get(handles.pop,X);
out = inX + 12;
set(handles.ans,'String',out)

However, I have some error in set and get function and thus I am in trouble. Help please.


Solution

  • To avoid using globals you can use the UserData property of the figure window (assuming the uiobjects are children of the same figure). For example:

    function pop_Callback(hObject, eventdata, handles)
    
    % ...
    
    set( ancestor(hObject,'figure'), 'UserData', X )
    

    and

    function push_Callback(hObject, eventdata, handles)
    
    inX = get( ancestor(hObject,'figure'), 'UserData' );
    out = inX + 12;
    set(handles.ans,'String',out)