Why does the 'handles' variable not contain the data I assigned?

2 views (last 30 days)
I have a GUI that I 've created in MATLAB. In a callback, I pass the handles variable as an input to another subfunction. In the subfunction, I add fields to the handles structure, and assign data to the fields. I then use GUIDATA to store the updated handles variable, such as in the following code:
% callback
function callback(hObject,eventdata,handles)
subfunction(handles);
v = handles.newfield;
% subfunction
function handles = subfunction(handles)
handles.newfield = 1;
guidata(handles.figure,handles)
When control returns from the subfunction to the callback, I attempt to use the newly added fields. However, this results in the following error message:
??? Reference to non-existent field 'fieldname'.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 22 Sep 2009
The subfunction has its own copy of the handles variable. If you store the modified variable from inside the subfunction, then the figure does have a copy of that updated variable. However, when you return to the callback function, it still has its original copy of the handles variable. Therefore, there are two possible courses of action:
1) Pass the handles variable as an output of the subfunction, and return the variable to the callback function as follows:
% callback
function callback(hObject,eventdata,handles)
handles = subfunction(handles);
v = handles.newfield;
% subfunction
function handles = subfunction(handles)
handles.newfield = 1;
guidata(handles.figure,handles)
This will pass the updated variable directly to the callback function.
2) Reload the handles variable after returning from the subfunction
% callback
function callback(hObject,eventdata,handles)
subfunction(handles);
handles = guidata(hObject)
v = handles.newfield;
% subfunction
function subfunction(handles)
handles.newfield = 1;
guidata(handles.figure,handles)
This will load the updated variable, from where it was stored with the figure.

More Answers (0)

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!