| Contents | Index |
| On this page… |
|---|
Most GUIs generate or use data specific to the application. GUI components often need to communicate data to one another and several basic mechanism serve this need.
Although many GUIs are single figures, you can make several GUIs work together if your application requires more than a single figure. For example, your GUI could require several dialog boxes to display and obtain some of the parameters used by the GUI. Your GUI could include several individual tools that work together, either at the same time or in succession. To avoid communication via files or workspace variables, you can use any of the methods described in the following table.
| Data-Sharing Method | How it Works | Use for... |
|---|---|---|
| Property/value pairs | Send data into a newly invoked or existing GUI by passing it along as input arguments. | Communicating data to new GUIs. |
| Output | Return data from the invoked GUI. | Communicating data back to the invoking GUI, such as passing back the handles structure of the invoked GUI |
| Function handles or private data | Pass function handles or data through one of the four following methods: | Exposing functionality within a GUI or between GUIs |
| Nested Functions: share the name space of all superior functions | Accessing and modifying variables defined in a directly or indirectly enclosing function, typically within a single GUI figure | |
| UserData: Store data in this figure or component property and communicate it to other GUIs via handle references. | Communicating data within a GUI or between GUIs; UserData is limited to one variable, often supplied as a struct | |
| Application Data (getappdata and setappdata): Store named data in a figure or component and communicate to other GUIs via handle references. | Communicating data within a GUI or between GUIs; any number or types of variables can be stored as application data through this API | |
| guidata: Store data in the handles structure of a GUI and communicate to other GUIs via handle references. | Communicating data within a GUI or between GUIs—a convenient way to manage application data. GUI Data is a struct associated with the GUI figure. |
The example Icon Editor further explains sharing data between GUI figures.
The next three sections describe mechanisms that provide a way to manage application-defined data, stored within a GUI:
Nested Functions — Share variables defined at a higher level and call one another when called function is below above, or a sibling of the caller.
UserData Property — A MATLAB workspace variable that you assign to GUI components and retrieve like any other property.
Application Data — Provides a way for applications to save and retrieve data associated with a specified object. For a GUI, this is usually the GUI figure, but it can also be any component. The data is stored as name/value pairs. Application data enables you to create what are essentially user-defined properties for an object.
GUI Data — Uses the guidata function to manage GUI data. This function can store a single variable as GUI data in a MATLAB structure, which in GUIDE is called the handles structure. You use the function to retrieve the handles structure, as well as to update it.
You can compare the three approaches applied to a simple working GUI in Examples of Sharing Data Among a GUI's Callbacks.
Nested functions enable callback functions to share data freely without requiring it to be passed as arguments, and helping you to:
Construct components, define variables, and generate data in the initialization segment of your code.
Nest the GUI callbacks and utility functions at a level below the initialization.
The callbacks and utility functions automatically have access to the data and the component handles because they are defined at a higher level. You can often use this approach to avoid storing UserData, application data, or GUIdata.
Note For the rules and restrictions that apply to using nested functions, see Nested Functions. |
All GUI components, including menus and the figure itself have a UserData property. You can assign any valid MATLAB workspace value as the UserData property's value, but only one value can exist at a time. To retrieve the data, a callback must know the handle of the component in which the data is stored. You access UserData using get and set with the appropriate object's handle. The following example illustrates this pattern:
An edit text component stores the user-entered string in its UserData property:
function mygui_edittext1(hObject, eventdata, handles) mystring = get(hObject,'String'); set(hObject,'UserData',mystring);
A menu item retrieves the string from the edit text component's UserData property. The callback uses the handles structure and the edit text's Tag property, edittext1, to specify the edit text handle:
function mygui_pushbutton1(hObject, eventdata, handles) string = get(handles.edittext1,'UserData');
For example, if the menu item is Undo, its code could reset the String of edittext1 back to the value stored in its UserData. To facilitate undo operations, the UserData can be a cell array of strings, managed as a stack or circular buffer.
Application data, like UserData, is arbitrary data that is meaningful to and defined by your application. Whether to use application data or UserData is a matter of choice. You attach application data to a figure or any GUI component (other than ActiveX controls) with the functions setappdata and getappdata, The main differences between it and UserData are:
You can assign multiple values to application data, but only one value to UserData
Your code must reference application data by name (like using a Tag), but can access UserData like any other property
Only Handle Graphics MATLAB objects use this property. The following table summarizes the functions that provide access to application data. For more details, see the individual function reference pages.
Functions for Managing Application Data
Function | Purpose |
|---|---|
Specify named application data for an object (a figure or other Handle Graphics object in your GUI). You can specify more than one named application data for an object. However, each name must be unique for that object and can be associated with only one value, usually a structure. | |
Retrieve named application data. To retrieve named application data, you must know the name associated with the application data and the handle of the object with which it is associated. If you specify a handle only, all the object's application data is returned. | |
True if the named application data exists, false otherwise. | |
Remove the named application data. |
Use the setappdata function to create application data. This example generates a 35-by-35 matrix of normally distributed random numbers in the opening function and creates application data mydata to manage it:
function mygui_OpeningFcn(hObject, eventdata, handles, varargin) matrices.rand_35 = randn(35); setappdata(hObject,'mydata',matrices);
Because this code appears in the opening function (mygui_OpeningFcn), hObject is the handle of the GUI figure, and the code sets mydata as application data for the figure.
Application data is usually defined as a structure. This enables you to add fields as necessary. In this example, a push button adds a field to the application data structure mydata created in the previous section:
Use getappdata to retrieve the structure.
The name of the application data structure is mydata. It is associated with the figure whose Tag is figure1. Since you pass the handles structure to every callback, the code specifies the figure's handle as handles.figure1:
function mygui_pushbutton1(hObject, eventdata, handles) matrices = getappdata(handles.figure1,'mydata');
Create a new field and assign it a value:
matrices.randn_50 = randn(50);
adds the field randn_50 to the matrices structure and sets it to a 50-by-50 matrix of normally distributed random numbers.
Use setappdata to save the data. This command uses setappdata to save the matrices structure as the application data structure mydata:
setappdata(handles.figure1,'mydata',matrices);
GUI data is always associated with the GUI figure and is available to all callbacks of all the GUI components created in GUIDE. If you specify a component handle when you save or retrieve GUI data, MATLAB software automatically associates the data with the component's parent figure. With GUI data:
You can access the data from within a callback routine using the component's handle, without needing to find the figure handle.
You do not need to create and maintain a hard-coded name for the data throughout your source code.
Use the guidata function to manage GUI data. This function can store a single variable as GUI data. GUI data differs from application data in that
GUI data is a single variable; however, when defined as a structure, you can add and remove fields.
Application data can consist of many variables, each stored under a separate unique name.
GUIDE uses GUI data to store its handles structure, to which you can add fields, but should not remove any.
You access GUI data using the guidata function, which both stores and retrieves GUI data.
Whenever you use guidata to store GUI data, it overwrites the existing GUI data.
Using the getappdata, setappdata, and rmappdata functions does not affect GUI data.
GUIDE uses guidata to create and maintain the handles structure. The handles structure contains the handles of all GUI components. GUIDE automatically passes the handles structure to every callback as an input argument.
In a GUI created using GUIDE, you cannot use guidata to manage any variable other than the handles structure. If you do, you can overwrite the handles structure and your GUI will not work. To use GUI data to share application-defined data among callbacks, you can store the data in fields that you add to the handles structure. See handles Structure for more information. The GUIDE templates use the handles structure to store application-defined data. See Select a GUI Template for information about the templates.
To add a field to the handles structure, which is passed as an argument to every callback in GUIDE, take these steps:
Assign a value to the new field. This adds the field to the structure. For example:
handles.number_errors = 0;
adds the field number_errors to the handles structure and sets it to 0.
Use the following command to save the data:
guidata(hObject,handles)
where hObject is the handle of the component for which the callback was triggered. GUIDE then automatically passes the hObject to every callback.
In GUIDE-generated code, the handles structure always represents GUI data. The next example updates the handles structure, and then saves it.
Assume that the handles structure contains an application-defined field handles.when whose value is 'now'.
Change the value of handles.when, to 'later' in a GUI callback. This does not save the handles structure.
handles.when = 'later';
Save the changed version of the handles structure with the command
guidata(hObject,handles)
where hObject is the handle of the component for which the callback was triggered. If you do not save the handles structure with guidata, you lose the change you made to it in the previous step.
You can declare a GUI to be a "singleton," which means only one instance of it can execute at one time. See GUI Allows Only One Instance to Run (Singleton). The CreateFcns of components in a singleton GUI are only called the first time it runs; subsequent invocations of the GUI do not execute the CreateFcns because all the objects already exist. However, the opening function is called every time a singleton GUI is invoked.
If your GUI performs initialization actions in its OpeningFcn, you might want some or all of them to occur only the first time the GUI runs. That is, if the user invoked the GUI again from the Command Line or by other means while it is currently running, its internal state might not need to be initialized again. One way to do that is to set a flag and store it in the handles structure. The opening function can test for the existence of the flag, and perform initialization operations only if the flag does not exist. The following code snippet illustrates this pattern:
function mygui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to spingui (see VARARGIN)
% Check whether initialization has already been performed
if ~isfield(handles,'initialized')
% Flag not present, so create and store it
handles.initialized = true;
guidata(hObject,handles)
% perform initialization; it will only happen once.
initialize_mygui() % Insert code or function call here
end
...The following examples illustrate the differences among three methods of sharing data between slider and edit text GUI components. It contains a slider and an edit text component as shown in the following figure. A static text component instructs the user to enter a value in the edit text or click the slider. When the user enters an invalid value, the edit text field displays an error message.

If the user types a number between 0 and 1 in the edit text component and then presses Enter or clicks outside the edit text, the callback sets handles.slider1 to the new value and the slider moves to the corresponding position.
If the entry is invalid—for example, 2.5—the GUI increments the value stored in the error counter and displays a message in the edit text component that includes the count of errors.

To obtain copies of the GUI files for this example, follow the steps listed below. If you are reading this in the MATLAB Help browser, you can access the example FIG-file and code file by clicking the following links. If you are reading this on the Web or in PDF form, you should go to the corresponding section in the MATLAB Help Browser to use the links.
If you intend to modify the layout or code of this GUI example, you should first save copies of its code file and FIG-file to your current folder. (You need write access to your current folder to do this.) Follow these steps to copy the example files to your current folder, and then open them:
Type guide sliderbox_userdata or click here to open the GUI in GUIDE.
Type edit sliderbox_userdata or click here to open the GUI code file in the Editor.
You can view the properties of any component by double-clicking it in the Layout Editor to open the Property Inspector for it. You can modify either the figure, GUI code, or both. Then you can save the GUI in your current folder using File > Save as from GUIDE. This saves both files, allowing you to rename them if you choose.
If you just want to run the GUI or inspect it in GUIDE, follow these steps:
Click here to add the example files to the MATLAB path (only for the current session).
Click here to display the GUI in the GUIDE Layout Editor (read-only).
Click here to display the GUI code file in the MATLAB Editor (read-only).
Note Do not save GUI files to the examples folder where you found them, or you will overwrite the original files. If you want to save the GUI files, use File > Save as from GUIDE, which saves both the GUI FIG-file and the GUI code file. |
How Sharing Data with UserData Works. 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 the property is associated. The code uses the get function to retrieve UserDataand the set function to set it.
Note For more information, see UserData Property |
This section shows you how to use GUI data to initialize and maintain an error counter by storing an error count in the edit text component's UserData property.
Add the following code to the opening function to initialize the edit text component's UserData property. This code initializes the data in a structure to allow for other data that could be needed:
% INITIALIZE ERROR COUNT AND USE EDITTEXT1 OBJECT'S USERDATA TO STORE IT. data.number_errors = 0; set(handles.edittext1,'UserData',data)
Add the following statement to set the edit text value from the slider callback:
set(handles.edittext1,'String',... num2str(get(hObject,'Value')));
where hObject is the handle of the slider.
Add the following lines of code to the edit text callback to set the slider value from the edit text callback:
val = str2double(get(hObject,'String'));
% Determine whether val is a number between 0 and 1.
if isnumeric(val) && length(val)==1 && ...
val >= get(handles.slider1,'Min') && ...
val <= get(handles.slider1,'Max')
set(handles.slider1,'Value',val);
else
% Retrieve and increment the error count.
% Error count is in the edit text UserData,
% so we already have its handle.
data = get(hObject,'UserData');
data.number_errors = data.number_errors+1;
% Save the changes.
set(hObject,'UserData',data);
% Display new total.
set(hObject,'String',...
['You have entered an invalid entry ',...
num2str(data.number_errors),' times.']);
% Restore focus to the edit text box after error
uicontrol(hObject)
endTo update the number of errors, the code must first retrieve the value of the edit text UserData property, and then it must increment the count. The code then saves the updated error count in the UserData property and displays the new count.
hObject is the handle of the edit text component because this code appears in the edit text callback. The next-to-last line of the callback
uicontrol(hObject)
is useful, although not necessary for the callback to work properly. The call to uicontrol has the effect of placing the edit text box in focus. An edit text control executes its callback after the user presses Return or clicks away from the control. These actions both cause the edit text box to lose focus. Restoring focus to it in the event of an error helps the user to understand what action triggered the error. The user can then correct the error by typing again in the edit text box.
To obtain copies of the GUI files for this example, follow the steps listed below. If you are reading this in the MATLAB Help browser, you can access the example FIG-file and code file by clicking the following links. If you are reading this on the Web or in PDF form, you should go to the corresponding section in the MATLAB Help Browser to use the links.
If you intend to modify the layout or code of this GUI example, you should first save copies of its code file and FIG-file to your current folder. (You need write access to your current folder to do this.) Follow these steps to copy the example files to your current folder, and then open them:
Type guide sliderbox_appdata or click here to open the GUI in GUIDE.
Type edit sliderbox_appdata or click here to open the GUI code file in the Editor.
You can view the properties of any component by double-clicking it in the Layout Editor to open the Property Inspector for it. You can modify either the figure, the code, or both. Then you can save the GUI in your current folder using File > Save as from GUIDE. This saves both files, allowing you to rename them if you choose.
If you just want to run the GUI or inspect it in GUIDE, follow these steps:
Click here to add the example files to the MATLAB path (only for the current session).
Click here to display the GUI in the GUIDE Layout Editor (read-only).
Click here to display the GUI code file in the MATLAB Editor (read-only).
Note Do not save GUI files to the examples folder where you found them, or you will overwrite the original files. If you want to save the GUI files, use File > Save as from GUIDE, which saves both the GUI FIG-file and the GUI code file. |
How Sharing Data with Application Data Works. You can associate application data 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 with which it is associated. Use the setappdata, getappdata, isappdata, and rmappdata functions to manage application data.
Note For more information, see Application Data . |
The section Sharing Data with GUI Data uses GUI data to initialize and maintain an error counter. This example shows you how to do the same thing using application data:
Define the error counter in the opening function by adding the following code to the opening function:
% INITIALIZE ERROR COUNT AND USE APPDATA API TO STORE IT IN FIGURE. slider_data.number_errors = 0; setappdata(hObject,'slider',slider_data);
This code first creates a structure slider_data, and then assigns it to the named application data slider. The hObject associates the application data with the figure, because this code appears in the opening function.
Convert the slider Value property to a string and set the value of the edit text component's String property from the slider callback by adding this statement to the callback:
set(handles.edittext1,'String',...
num2str(get(hObject,'Value')));
Because this statement appears in the slider callback, hObject is the handle of the slider.
Set the slider value from the edit text component's callback. Add the following code to the callback. It assumes the figure's Tag property is figure1.
To update the number of errors, this code must first retrieve the named application data slider, and then it must increment the count. The code then saves the application data and displays the new error count.
val = str2double(get(hObject,'String')); % Determine whether val is a number between 0 and 1. if isnumeric(val) && length(val)==1 && ... val >= get(handles.slider1,'Min') && ... val <= get(handles.slider1,'Max') set(handles.slider1,'Value',val); else % Retrieve and increment the error count. slider_data = getappdata(handles.figure1,'slider'); slider_data.number_errors = slider_data.number_errors+1; % Save the changes. setappdata(handles.figure1,'slider',slider_data); % Display new total. set(hObject,'String',... ['You have entered an invalid entry ',... num2str(slider_data.number_errors),' times.']); end
hObject is the handle of the edit text component because this code appears in the edit text callback. The next-to-last line of the callback
uicontrol(hObject)
is useful, although not necessary for the callback to work properly. The call to uicontrol has the effect of placing the edit text box in focus. An edit text control executes its callback after the user presses Return or clicks away from the control. These actions both cause the edit text box to lose focus. Restoring focus to it in the event of an error helps the user to understand what action triggered the error. The user can then correct the error by typing again in the edit text box.
To obtain copies of the GUI files for this example, follow the steps listed below. If you are reading this in the MATLAB Help browser, you can access the example FIG-file and code file by clicking the following links. If you are reading this on the Web or in PDF form, you should go to the corresponding section in the MATLAB Help Browser to use the links.
If you intend to modify the layout or code of this GUI example, you should first save copies of its code file and FIG-file to your current folder. (You need write access to your current folder to do this.) Follow these steps to copy the example files to your current folder, and then open them:
guide sliderbox_guidata or click here to open the GUI in GUIDE.
edit sliderbox_guidata or click here to open the GUI code file in the Editor.
You can view the properties of any component by double-clicking it in the Layout Editor to open the Property Inspector for it. You can modify either the figure, the code, or both. Then you can save the GUI in your current folder using File > Save as from GUIDE. This saves both files, allowing you to rename them if you choose.
If you just want to run the GUI or inspect it in GUIDE, follow these steps:
Click here to add the example files to the MATLAB path (only for the current session).
Click here to display the GUI in the GUIDE Layout Editor (read-only).
Click here to display the GUI code file in the MATLAB Editor (read-only).
Note Do not save GUI files to the examples folder where you found them, or you will overwrite the original files. If you want to save the GUI files, use File > Save as from GUIDE, which saves both the GUI FIG-file and the GUI code file. |
How Sharing Data with GUI Data Works. All GUI callbacks can access GUI data. A callback for one component can set a value in GUI data, which, a callback for another component can then read. This example uses GUI data to initialize and maintain an error counter.
Note For more information, see GUI Data . |
The GUI behavior is as follows:
When a user moves the slider, the edit text component displays the slider's current value.
When a user types a value into the edit text component, the slider updates to this value.
If a user enters a value in the edit text that is out of range for the slider (a value that is not between 0 and 1), the application returns a message in the edit text component that indicates the number of times the user entered an incorrect value.
The commands in the following steps initialize the error counter and implement the interchange between the slider and the edit text component:
Define the error counter in the opening function. The GUI records the number of times a user enters an incorrect value in the edit text component and stores this number in a field of the handles structure.
Define the number_errors field in the opening function as follows:
% INITIALIZE ERROR COUNT AND USE GUIDATA TO UPDATE THE HANDLES STRUCTURE. handles.number_errors = 0;
Place it above the following line, which GUIDE automatically inserts into the opening function:
guidata(hObject,handles);
The guidata command saves the modified handles structure so that it can be retrieved in the GUI's callbacks.
Set the value of the edit text component String property from the slider callback. The following command in the slider callback updates the value displayed in the edit text component when a user moves the slider and releases the mouse button:
set(handles.edittext1,'String',... num2str(get(handles.slider1,'Value')));
This code combines three commands:
The get command obtains the current value of the slider.
The num2str command converts the value to a string.
The set command sets the String property of the edit text to the updated value.
Set the slider value from the edit text component's callback. The edit text component's callback sets the slider's value to the number the user enters, after checking to see if it is a single numeric value between 0 and 1. If the value is out of range, the error count increments and the edit text displays a message telling the user how many times they entered an invalid number. Because this code appears in the edit text component's callback, hObject is the handle of the edit text component:
val = str2double(get(hObject,'String'));
% Determine whether val is a number between 0 and 1.
if isnumeric(val) && length(val)==1 && ...
val >= get(handles.slider1,'Min') && ...
val <= get(handles.slider1,'Max')
set(handles.slider1,'Value',val);
else
% Increment the error count, and display it.
handles.number_errors = handles.number_errors+1;
guidata(hObject,handles); % Store the changes.
set(hObject,'String',...
['You have entered an invalid entry ',...
num2str(handles.number_errors),' times.']);
% Restore focus to the edit text box after error
uicontrol(hObject)
endhObject is the handle of the edit text component because this code appears in the edit text callback. The next-to-last line of the callback
uicontrol(hObject)
is useful, although not necessary for the callback to work properly. The call to uicontrol has the effect of placing the edit text box in focus. An edit text control executes its callback after the user presses Return or clicks away from the control. These actions both cause the edit text box to lose focus. Restoring focus to it in the event of an error helps the user to understand what action triggered the error. The user can then correct the error by typing again in the edit text box.
![]() | Managing and Sharing Application Data in GUIDE | Making Multiple GUIs Work Together | ![]() |

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