| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
| On this page… |
|---|
Sharing Data with Nested Functions |
The following four sections each contain complete code for example GUIs that you can copy to M-files and run. For general information about these methods, see Mechanisms for Managing Data.
You can use GUI data, application data, and the UserData property to share data among a GUI's callbacks. In many cases, nested functions enable you to share data among callbacks without using the other data forms.
This example uses a GUI that contains a slider and an edit text component. A static text component instructs the user to enter a value in the edit text or click the slider. The example initializes and maintains an error counter, as well as the old and new values of the slider, in a nested functions environment.

The GUI behavior is as follows:
When a user moves the slider, the edit text component displays the slider's current value and prints a message to the Command Window indicating how far the slider moved from its previous position.
You changed the slider value by 24.11 percent.
When a user types a value into the edit text component and then presses Enter or clicks outside the component, the slider also updates to the value entered and the edit text component prints a message to the Command Window indicating how many units the slider moved.
If a user enters a value in the edit text component that is out of range for the slider—that is, a value that is not between the slider's Min and Max properties—the application returns a message in the edit text indicating how many times the user has entered an erroneous value.

The following code constructs the components, initializes the error counter, and the previous and new slider values in the initialization section of the function, and uses two callbacks to implement the interchange between the slider and the edit text component. The slider callback and text edit callback are nested within the main function.
You can copy the following code listing, paste it into a new M-file, and save it in your current folder, or elsewhere on your path, as slider_gui_nested.m. Alternatively, click here to place slider_gui_nested.m in your current folder. Run the function by typing slider_gui_nested at the command line.
function slider_gui_nested
fh = figure('Position',[250 250 350 350],...
'MenuBar','none','NumberTitle','off',...
'Name','Sharing Data with Nested Functions');
sh = uicontrol(fh,'Style','slider',...
'Max',100,'Min',0,'Value',25,...
'SliderStep',[0.05 0.2],...
'Position',[300 25 20 300],...
'Callback',@slider_callback);
eth = uicontrol(fh,'Style','edit',...
'String',num2str(get(sh,'Value')),...
'Position',[30 175 240 20],...
'Callback',@edittext_callback);
sth = uicontrol(fh,'Style','text','String',...
'Enter a value or click the slider.',...
'Position',[30 215 240 20]);
number_errors = 0;
previous_val = 0;
val = 0;
% ------------First Nested Function---------------
% Set the value of the edit text component String property
% to the value of the slider.
function slider_callback(hObject,eventdata)
previous_val = val;
val = get(hObject,'Value');
set(eth,'String',num2str(val));
sprintf('You changed the slider value by %6.2f percent.',...
abs(val - previous_val))
end
% ---------------Second Nested Function----------------
% Set the slider value to the number the user types in
% the edit text or display an error message.
function edittext_callback(hObject,eventdata)
previous_val = val;
val = str2double(get(hObject,'String'));
% Determine whether val is a number between the
% slider's Min and Max. If it is, set the slider Value.
if isnumeric(val) && length(val) == 1 && ...
val >= get(sh,'Min') && ...
val <= get(sh,'Max')
set(sh,'Value',val);
sprintf('You changed the slider value by %6.2f percent.',...
abs(val - previous_val))
else
% Increment the error count, and display it.
number_errors = number_errors+1;
set(hObject,'String',...
['You have entered an invalid entry ',...
num2str(number_errors),' times.']);
val = previous_val;
end
end
endBecause the components are constructed at the top level, their handles are immediately available to the callbacks that are nested at a lower level of the routine. The same is true of the error counter, number_errors, the previous slider value, previous_val, and the new slider value, val. You do not need to pass these variables as arguments.
Both callbacks use the input argument hObject to get and set properties of the component that triggered execution of the callback. This argument is available to the callbacks because the components' Callback properties are specified as function handles. For more information, see Providing Callbacks for Components.
Slider Callback. The slider callback, slider_callback, uses the edit text component handle, eth, to set the edit text 'String' property to the value that the user typed.
The slider Callback saves the previous value, val, of the slider in previous_val before assigning the new value to val. These variables are known to both callbacks because they are initialized at a higher level. They can be retrieved and set by either callback.
previous_val = val; val = get(hObject,'Value');
The following statements in the slider callback update the value displayed in the edit text component when a user moves the slider and releases the mouse button.
val = get(hObject,'Value'); set(eth,'String',num2str(val));
The code combines three commands:
get obtains the current value of the slider.
num2str converts the value to a string.
set sets the String property of the edit text component to the updated value.
Edit Text Callback. The callback for edit text, edittext_callback, uses the slider handle, sh, to determine the slider's Max and Min properties and to set the slider Value property, which determine the position of the slider thumb.
The edit text callback uses the following code to set the slider's value to the number that the user enters, after checking to see if it is a single numeric value within the allowed range.
if isnumeric(val) && length(val) == 1 && ... val >= get(sh,'Min') && ... val <= get(sh,'Max') set(sh,'Value',val);
If the value is out of range, the if statement continues by incrementing the error counter, number_errors, and displaying a message telling the user how many times they have entered an invalid number.
else number_errors = number_errors+1; set(hObject,'String',... ['You have entered an invalid entry ',... num2str(number_errors),' times.']); end
Every GUI component, and the figure itself, has a UserData property that you can use to store application-defined data. To access UserData, a callback must know the handle of the component with which a specific UserData property is associated.
Use the get function to retrieve UserData, and the set function to set it.
The following code is the same as in the prior example, Sharing Data with Nested Functions, but uses the UserData property to initialize and increment the error counter. It also uses nested functions to provide callbacks with access to other component's handles, which the main function defines. You can copy the following code listing, paste it into a new M-file, and save it in your current folder, or elsewhere on your path, as slider_gui_userdata.m. Alternatively, click here to place slider_gui_userdata.m in your current folder. Run the function by typing slider_gui_userdata at the command line.
function slider_gui_userdata
fh = figure('Position',[250 250 350 350],...
'MenuBar','none','NumberTitle','off',...
'Name','Sharing Data with UserData');
sh = uicontrol(fh,'Style','slider',...
'Max',100,'Min',0,'Value',25,...
'SliderStep',[0.05 0.2],...
'Position',[300 25 20 300],...
'Callback',@slider_callback);
eth = uicontrol(fh,'Style','edit',...
'String',num2str(get(sh,'Value')),...
'Position',[30 175 240 20],...
'Callback',@edittext_callback);
sth = uicontrol(fh,'Style','text','String',...
'Enter a value or click the slider.',...
'Position',[30 215 240 20]);
number_errors = 0;
slider.val = 25;
% Set edit text UserData property to slider structure.
set(eth,'UserData',slider)
% ----------------------------------------------------
% Set the value of the edit text component String property
% to the value of the slider.
function slider_callback(hObject,eventdata)
% Get slider from edit text UserData.
slider = get(eth,'UserData');
slider.previous_val = slider.val;
slider.val = get(hObject,'Value');
set(eth,'String',num2str(slider.val));
sprintf('You changed the slider value by %6.2f percent.',...
abs(slider.val - slider.previous_val))
% Save slider in UserData before returning.
set(eth,'UserData',slider)
end
% ----------------------------------------------------
% Set the slider value to the number the user types in
% the edit text or display an error message.
function edittext_callback(hObject,eventdata)
% Get slider from edit text UserData.
slider = get(eth,'UserData');
slider.previous_val = slider.val;
slider.val = str2double(get(hObject,'String'));
% Determine whether slider.val is a number between the
% slider's Min and Max. If it is, set the slider Value.
if isnumeric(slider.val) && ...
length(slider.val) == 1 && ...
slider.val >= get(sh,'Min') && ...
slider.val <= get(sh,'Max')
set(sh,'Value',slider.val);
sprintf('You changed the slider value by %6.2f percent.',...
abs(slider.val - slider.previous_val))
else
% Increment the error count, and display it.
number_errors = number_errors+1;
set(hObject,'String',...
['You have entered an invalid entry ',...
num2str(number_errors),' times.']);
slider.val = slider.previous_val;
end
% Save slider structure in UserData before returning.
set(eth,'UserData',slider)
end
endSlider Values. In this example, both the slider callback, slider_callback and the edit text callback, edittext_callback, retrieve the structure slider from the edit text UserData property. The slider structure holds previous and current values of the slider. The callbacks then save the value slider.val to slider.previous_val before retrieving the new value and assigning it to slider.val. Before returning, each callback saves the slider structure in the edit text UserData property.
% Get slider structure from edit text UserData. slider = get(eth,'UserData',slider); slider.previous_val = slider.val; slider.val = str2double(get(hObject,'String')); ... % Save slider structure in UserData before returning. set(eth,'UserData',slider)
Both callbacks use the get and set functions to retrieve and save the slider structure in the edit text UserData property.
Application data can be associated with any object—a component, menu, or the figure itself. To access application data, a callback must know the name of the data and the handle of the component in which it is stored. Use the functions setappdata, getappdata, isappdata, and rmappdata to manage application data.
For more information about application data, see Application Data.
The following code is similar to the previous examples, but uses application data to initialize and maintain the old and new slider values in the edit text and slider Callbacks. It also uses nested functions to provide callbacks with access to other components' handles, which the main function defines. You can copy the following code listing, paste it into a new M-file, and save it in your current folder, or elsewhere on your path, as slider_gui_appdata.m. Alternatively, click here to place slider_gui_appdata.m in your current folder. Run the function by typing slider_gui_appdata at the command line.
function slider_gui_appdata
fh = figure('Position',[250 250 350 350],...
'MenuBar','none','NumberTitle','off',...
'Name','Sharing Data with Application Data');
sh = uicontrol(fh,'Style','slider',...
'Max',100,'Min',0,'Value',25,...
'SliderStep',[0.05 0.2],...
'Position',[300 25 20 300],...
'Callback',@slider_callback);
eth = uicontrol(fh,'Style','edit',...
'String',num2str(get(sh,'Value')),...
'Position',[30 175 240 20],...
'Callback',@edittext_callback);
sth = uicontrol(fh,'Style','text','String',...
'Enter a value or click the slider.',...
'Position',[30 215 240 20]);
number_errors = 0;
slider_data.val = 25;
% Create appdata with name 'slider'.
setappdata(fh,'slider',slider_data);
% ----------------------------------------------------
% Set the value of the edit text component String property
% to the value of the slider.
function slider_callback(hObject,eventdata)
% Get 'slider' appdata.
slider_data = getappdata(fh,'slider');
slider_data.previous_val = slider_data.val;
slider_data.val = get(hObject,'Value');
set(eth,'String',num2str(slider_data.val));
sprintf('You changed the slider value by %6.2f percent.',...
abs(slider_data.val - slider_data.previous_val))
% Save 'slider' appdata before returning.
setappdata(fh,'slider',slider_data)
end
% ----------------------------------------------------
% Set the slider value to the number the user types in
% the edit text or display an error message.
function edittext_callback(hObject,eventdata)
% Get 'slider' appdata.
slider_data = getappdata(fh,'slider');
slider_data.previous_val = slider_data.val;
slider_data.val = str2double(get(hObject,'String'));
% Determine whether val is a number between the
% slider's Min and Max. If it is, set the slider Value.
if isnumeric(slider_data.val) && ...
length(slider_data.val) == 1 && ...
slider_data.val >= get(sh,'Min') && ...
slider_data.val <= get(sh,'Max')
set(sh,'Value',slider_data.val);
sprintf('You changed the slider value by %6.2f percent.',...
abs(slider_data.val - slider_data.previous_val))
else
% Increment the error count, and display it.
number_errors = number_errors+1;
set(hObject,'String',...
['You have entered an invalid entry ',...
num2str(number_errors),' times.']);
slider_data.val = slider_data.previous_val;
end
% Save appdata before returning.
setappdata(fh,'slider',slider_data);
end
endSlider Values. In this example, both the slider callback, slider_callback, and the edit text callback, edittext_callback, retrieve the slider_data application data structure, which holds previous and current values of the slider. They then save the value, slider_data.val to slider_data.previous_val before retrieving the new value and assigning it to slider_data.val. Before returning, each callback saves the slider_data structure in the slider application data.
% Get 'slider' appdata. slider_data = getappdata(fh,'slider'); slider_data.previous_val = slider_data.val; slider_data.val = str2double(get(hObject,'String')); ... % Save 'slider' appdata before returning. setappdata(fh,'slider',slider_data)
Both callbacks use the getappdata and setappdata functions to retrieve and save the slider_data structure as slider application data.
GUI data, which you manage with the guidata function, is accessible to all callbacks of the GUI. A callback for one component can set a value in GUI data, which can then be read by a callback for another component. For more information, see GUI Data.
The following code is similar to the code of the previous topic, but uses GUI data to initialize and maintain the old and new slider values in the edit text and slider callbacks. It also uses nested functions to provide callbacks with access to other component's handles, which the main function defines. You can copy the following code listing, paste it into a new M-file, and save it in your current folder, or elsewhere on your path, as slider_gui_guidata.m. Alternatively, click here to place slider_gui_guidata.m in your current folder. Run the function by typing slider_gui_guidata at the command line.
function slider_gui_guidata
fh = figure('Position',[250 250 350 350],...
'MenuBar','none','NumberTitle','off',...
'Name','Sharing Data with GUI Data');
sh = uicontrol(fh,'Style','slider',...
'Max',100,'Min',0,'Value',25,...
'SliderStep',[0.05 0.2],...
'Position',[300 25 20 300],...
'Callback',@slider_callback);
eth = uicontrol(fh,'Style','edit',...
'String',num2str(get(sh,'Value')),...
'Position',[30 175 240 20],...
'Callback',@edittext_callback);
sth = uicontrol(fh,'Style','text','String',...
'Enter a value or click the slider.',...
'Position',[30 215 240 20]);
number_errors = 0;
slider.val = 25;
guidata(fh,slider);
% ----------------------------------------------------
% Set the value of the edit text component String property
% to the value of the slider.
function slider_callback(hObject,eventdata)
slider = guidata(fh); % Get GUI data.
slider.previous_val = slider.val;
slider.val = get(hObject,'Value');
set(eth,'String',num2str(slider.val));
sprintf('You changed the slider value by %6.2f percent.',...
abs(slider.val - slider.previous_val))
guidata(fh,slider) % Save GUI data before returning.
end
% ----------------------------------------------------
% Set the slider value to the number the user types in
% the edit text or display an error message.
function edittext_callback(hObject,eventdata)
slider = guidata(fh); % Get GUI data.
slider.previous_val = slider.val;
slider.val = str2double(get(hObject,'String'));
% Determine whether slider.val is a number between the
% slider's Min and Max. If it is, set the slider Value.
if isnumeric(slider.val) && length(slider.val) == 1 && ...
slider.val >= get(sh,'Min') && ...
slider.val <= get(sh,'Max')
set(sh,'Value',slider.val);
sprintf('You changed the slider value by %6.2f percent.',...
abs(slider.val - slider.previous_val))
else
% Increment the error count, and display it.
number_errors = number_errors+1;
set(hObject,'String',...
['You have entered an invalid entry ',...
num2str(number_errors),' times.']);
slider.val = slider.previous_val;
end
guidata(fh,slider); % Save the changes as GUI data.
end
endSlider Values. In this example, both the slider callback, slider_callback, and the edit text callback, edittext_callback, retrieve the GUI data structure slider which hold previous and current values of the slider. They then save the value, slider.val to slider.previous_val before retrieving the new value and assigning it to slider.val. Before returning, each callback saves the slider structure to GUI data.
slider = guidata(fh); % Get GUI data. slider.previous_val = slider.val; slider.val = str2double(get(hObject,'String')); ... guidata(fh,slider) % Save GUI data before returning.
Both callbacks use the guidata function to retrieve and save the slider structure as GUI data.
![]() | Mechanisms for Managing Data | Managing Callback Execution | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |