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

9 次查看(过去 30 天)
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.

回答(1 个)

Stephen23
Stephen23 2018-8-31
编辑:Stephen23 2018-8-31
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 个评论
Mech Stud
Mech Stud 2018-8-31
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).

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Migrate GUIDE Apps 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by