Clear Filters
Clear Filters

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

9 views (last 30 days)
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;
set(handles.ans,'String',out)
However, I have some error in set and get function.

Answers (1)

Stephen23
Stephen23 on 31 Aug 2018
Edited: Stephen23 on 31 Aug 2018
At the end of a callback handles is not stored automatically, or somehow passed to other callbacks/functions. You have to do this explicitly, by calling guidata at the end of the callback:
guidata(hObject,handles)
Only then can you get .pop in the other callback. See the examples in the documentation:
  1 Comment
Mech Stud
Mech Stud on 31 Aug 2018
Thanks for the guidance. I read and edited my code as follows
contents = cellstr(get(hobject,'String'));
A = contents{get(hObject,'Value')}
data = guidata(object_handle);
if (strcmp(A,'C1'))
data = 10;
elseif (strcmp(A,'C2'))
data = 20;
end
guidata(object_handle,data)
set(handles.pop,data)
function push_Callback(hObject, eventdata, handles)
in = get(handles.pop,'String');
answ = in;
set(handles.ans,'String',answ)
However, The 'answ' is C1 and C2 (The 'Value' or the pull down menu option).

Sign in to comment.

Categories

Find more on Migrate GUIDE Apps in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!