GUI Push Button Undefined Variable
Show older comments
I am attempting to create a GUI with a push button that solves some equations for me. The data that it is using is gained from some edit text boxes. This is how the data is being read in:
function edit2_Callback(hObject, eventdata, handles)
r = str2double(get(handles.edit2,'string'));
assignin('base','r',r)
In my workspace, the variable r shows up as the value that was inputted. In the push button callback I am attempting to access that variable and it shows up with an error of "Reference to non-existent field 'r'".
This is what my code for the push button looks like:
function pushbutton1_Callback(hObject, eventdata, handles)
%%Find Chi
r1 = 2*handles.r+2;
r2 = 2*handles.r;
I have tried removing the handles from this expression as well and that gave me the same error.
Answers (1)
Geoff Hayes
on 17 Feb 2016
Sara - the handles structure does not reference those variables that you save to the workspace. It only includes the handles to the GUI controls and any user-defined data that you have saved to the structure using guidata. As such, you can access your edit2 control directly through the handles object. Remove the edit2_Callback function, and within the push button callback do
function pushbutton1_Callback(hObject, eventdata, handles)
r = str2double(char(get(handles.edit2,'String')));
%%Find Chi
r1 = 2*r+2;
r2 = 2*r;
% etc.
Try the above and see what happens!
As an aside, in your edit2_Callback you do the following
r = str2double(get(handles.edit2,'string'));
In this case, you don't need to access handles as hObject is handles.edit2.
2 Comments
Sara Koniecko
on 18 Feb 2016
Geoff Hayes
on 18 Feb 2016
Yes, Sara. Just do the same as above, using the tag of the control as a field within handles. For example,
get(handles.edit1,'String');
get(handles.edit2,'String');
etc.
Categories
Find more on Programming Utilities 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!