MATLAB: Trouble with function called from a GUI callback fonction

guide callback and handlesMATLAB

I use GUIDE to make an interface.
I obtain some callbacks in wich I want to use another function as follow:
function CallbackFunction(hObject, eventdata, handles)
...
myFunction(hObject, eventdata, handles);
...
guidata(hObject, handles);
end % function
fucntion myFunction(hObject, eventdata, handles)
...
handles.Var=
guidata(hObject, handles);
end % fonction
But this seems to cause me many problems. I seem to miss something.
I just want to write a function that is called from a callback function and that can change handles variables?

Best Answer

Claude - look closely at the order in which handles is updated. The
function CallbackFunction(hObject, eventdata, handles)
is called passing in the latest (at the time) version of handles. This parameter (along with the other two) are passed in to your function
function myFunction(hObject, eventdata, handles)
where the code updates the handles object and then saves it using
guidata(hObject, handles);
But then we return back to your CallbackFunction and maybe do something, and then calls
guidata(hObject, handles);
But which version of handles is this? This is the copy that was passed into this function when CallbackFunction was called. It is not the updated version from your call to myFunction since myFunction does not return the updated handles structure, and your code probably doesn't refresh handles (after this call to myFunction) with
handles = guidata(hObject);
So you can do at least two different things - return the updated handles structure from myFunction by changing its signature to
function [handles] = myFunction(hObject, eventdata, handles);
and so your code would become something like
function CallbackFunction(hObject, eventdata, handles)
...
handles = myFunction(hObject, eventdata, handles);
...
guidata(hObject, handles); % in case you've updated handles again

end % function

Or you can refresh your local copy as
function CallbackFunction(hObject, eventdata, handles)
...
myFunction(hObject, eventdata, handles);
handles = guidata(hObject);
...
guidata(hObject, handles); % in case you've updated handles again
end % function
Hopefully, one of the above solutions will work for you!