Share Data Among Callbacks
slider = uicontrol('Parent', hfig,'Style','slider',...
'Units','normalized',...
'Position',[0.3 0.5 0.4 0.1],...
'Tag','slider1',...
'Callback',@slider_callback);
button = uicontrol('Parent', hfig,'Style','pushbutton',...
'Units','normalized',...
'Position',[0.4 0.3 0.2 0.1],...
'String','Display Values',...
'Callback',@button_callback);
end
function slider_callback(hObject,eventdata)
diffMax = hObject.Max - hObject.Value;
setappdata(hObject.Parent,'slidervalue',hObject.Value);
setappdata(hObject.Parent,'difference',diffMax);
end
function button_callback(hObject,eventdata)
currentval = getappdata(hObject.Parent,'slidervalue');
diffval = getappdata(hObject.Parent,'difference');
display([currentval diffval]);
end
When the user moves the slider, the slider_callback function calls setappdata to
save the new slider value using the name, 'slidervalue'. The next line of code calls
setappdata to save another value, diffMax, using the name, 'difference'. Both
calls to setappdata store the data in the figure.
When the user clicks the push button, the button_callback function calls getappdata
to retrieve the values named 'slidervalue' and 'difference'. Then, the final
command in the button_callback function displays those values.
If you are developing a UI using GUIDE, you can use setappdata and getappdata in
the same way.
Create Nested Callback Functions (Programmatic UIs)
You can nest callback functions inside the main function of a programmatic UI. When
you do this, the nested callback functions share a workspace with the main function. As a
result, the nested functions have access to all the UI components and variables defined in
the main function. The following example code uses nested functions to share data about