Documentation

This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.

Share Data Among Callbacks

Overview of Data Sharing Techniques

Many UIs contain interdependent controls, menus, and graphics objects. Since each callback function has its own scope, you must explicitly share data with those parts of your UI that need to access it. The table below describes several different methods for sharing data within your UI.

MethodDescriptionRequirements and Trade-Offs
Store Data in UserData or Other Object Properties

Query or store property values directly though the component object.

All UI components have a UserData property that can store any MATLAB® data.

  • Requires access to the component to set or retrieve the properties.

  • UserData holds only one variable at a time, but you can store multiple values as a struct array or cell array.

Store Data as Application Data

Associate data with a specific component using the setappdata function. You can access it later using the getappdata function.

  • Requires access to the component to set or retrieve the application data.

  • Can share multiple variables.

Create Nested Callback Functions (Programmatic UIs)

Nest your callback functions inside your main function. This gives your callback functions access to all the variables in the main function.

  • Requires callback functions to be coded in the same file as the main function.

  • Not recommended for GUIDE UIs.

  • Can share multiple variables.

Store Data Using the guidata Function

Share data with the figure window using the guidata function.

  • Stores or retrieves the data through any UI component.

  • Stores only one variable at a time, but you can store multiple values as a struct array or cell array.

Store Data in UserData or Other Object Properties

UI components contain useful information in their properties. For example, you can find the current position of a slider by querying its Value property. In addition, all components have a UserData property, which can store any MATLAB variable. All callback functions can access the value stored in the UserData property as long as those functions can access the component.

Share UserData in UIs Created Programmatically

Use dot notation, component.propertyname, to store or retrieve property values programmatically. Dot notation works in R2014b and later releases. This code queries and modifies the name of a figure.

hfig = figure;
figname = hfig.Name;
hfig.Name = 'My Window';
If you are using an earlier release, use the get and set functions instead:
hfig = figure;
figname = get(hfig,'Name');
set(hfig,'Name','My Window');

If your code does not have direct access to a component, use the findobj function to search for that component. If the search is successful, findobj returns the component as output. Then you can access the component's properties.

The following UI code uses the UserData property to share information about the slider. To see how it works, copy and paste this code into an editor and run it.

function my_slider()
hfig = figure();
slider = uicontrol('Parent', hfig,'Style','slider',...
         'Units','normalized',...
         'Position',[0.3 0.5 0.4 0.1],...
         'Tag','slider1',...
         'UserData',struct('val',0,'diffMax',1),...
         'Callback',@slider_callback);
     
button = uicontrol('Parent', hfig,'Style','pushbutton',...
         'Units','normalized',...
         'Position',[0.4 0.3 0.2 0.1],...
         'String','Display Difference',...
         'Callback',@button_callback);
end

function slider_callback(hObject,eventdata)
	sval = hObject.Value;
	diffMax = hObject.Max - sval;
	data = struct('val',sval,'diffMax',diffMax);
	hObject.UserData = data;
	% For R2014a and earlier: 
	% sval = get(hObject,'Value');  
	% maxval = get(hObject,'Max');  
	% diffMax = maxval - sval;      
	% data = struct('val',sval,'diffMax',diffMax);   
	% set(hObject,'UserData',data);   

end

function button_callback(hObject,eventdata)
	h = findobj('Tag','slider1');
	data = h.UserData;
	% For R2014a and earlier: 
	% data = get(h,'UserData'); 
	display([data.val data.diffMax]);
end
When the user moves the slider, the slider_callback uses these commands to store data in a structure:

  • data = struct('val',sval,'diffMax',diffMax) stores the values, sval and diffMax, in a structure called data.

  • hObject.UserData = data stores the value of data in the UserData property of the slider.

When the user clicks the push button, the button_callback uses these commands to retrieve the data:

  • h = findobj('Tag','slider1') finds the slider component.

  • data = h.UserData gets the value of the slider's UserData property.

Share UserData in GUIDE UIs

To set up a GUIDE UI for sharing slider data with the UserData property, perform these steps:

  1. In the Command Window, type guide.

  2. In the GUIDE Quick Start dialog box, select Blank GUI (Default). Then, click OK.

  3. Display the names of the UI components in the component palette:

    1. Select File > Preferences > GUIDE.

    2. Select Show names in component palette.

    3. Click OK.

  4. Select the push button tool from the component palette at the left side of the Layout Editor and drag it into the layout area.

  5. Select the slider tool from the component palette at the left side of the Layout Editor and drag it into the layout area.

  6. Select File > Save. Save the UI as myslider.fig. MATLAB opens the code file in the Editor.

  7. Set the initial value of the UserData property in the opening function, myslider_OpeningFcn. This function executes just before the UI is visible to users.

    In myslider_OpeningFcn, insert these commands immediately after the command, handles.output = hObject.

    data = struct('val',0,'diffMax',1);
    set(handles.slider1,'UserData',data);
    
    After you add the commands, myslider_OpeningFcn looks like this.
    function myslider_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 junk (see VARARGIN)
    
    % Choose default command line output for myslider
    handles.output = hObject;
    data = struct('val',0,'diffMax',1);
    set(handles.slider1,'UserData',data);
    
    % Update handles structure
    guidata(hObject, handles);
    
    % UIWAIT makes myslider wait for user response
    % uiwait(handles.figure1);
    
    Notice that handles is an input argument to myslider_OpeningFcn. The handles variable is a structure that contains all the components in the UI. Each field in this structure corresponds to a separate component. Each field name matches the Tag property of the corresponding component. Thus, handles.slider1 is the slider component in this UI. The command, set(handles.slider1,'UserData',data) stores the variable, data, in the UserData property of the slider.

  8. Add code to the slider callback for modifying the data. Add these commands to the end of the function, slider1_Callback.

    maxval = get(hObject,'Max');  
    sval = get(hObject,'Value');  
    diffMax = maxval - sval;   
    data = get(hObject,'UserData');
    data.val = sval;
    data.diffMax = diffMax;
    % Store data in UserData of slider
    set(hObject,'UserData',data);
    After you add the commands, slider1_Callback looks like this.
    % --- Executes on slider movement.
    function slider1_Callback(hObject, eventdata, handles)
    % hObject    handle to slider1 (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    
    % Hints: get(hObject,'Value') returns position of slider
    %        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
    maxval = get(hObject,'Max');  
    sval = get(hObject,'Value');  
    diffMax = maxval - sval;   
    data = get(hObject,'UserData');
    data.val = sval;
    data.diffMax = diffMax;
    % Store data in UserData of slider
    set(hObject,'UserData',data);
    
    Notice that hObject is an input argument to the slider1_Callback function. hObject is always the component that triggers the callback (the slider, in this case). Thus, set(hObject,'UserData',data), stores the data variable in the UserData property of the slider.

  9. Add code to the push button callback for retrieving the data. Add these commands to the end of the function, pushbutton1_Callback.

    % Get UserData from the slider
    data = get(handles.slider1,'UserData');
    currentval = data.val;
    diffval = data.diffMax;
    display([currentval diffval]);
    After you add the commands, pushbutton1_Callback looks like this.

    % --- Executes on button press in pushbutton1.
    function pushbutton1_Callback(hObject, eventdata, handles)
    % hObject    handle to pushbutton1 (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    
    % Get UserData from the slider
    data = get(handles.slider1,'UserData');
    currentval = data.val;
    diffval = data.diffMax;
    display([currentval diffval]);

    This code uses the handles structure to access the slider. The command, data = get(handles.slider1,'UserData'), gets the slider's UserData property. Then, the display function displays the stored values.

  10. Save your code by pressing Save in the Editor Toolstrip.

Store Data as Application Data

To store application data, call the setappdata function:

setappdata(obj,name,value);
The first input, obj, is the component object in which to store the data. The second input, name, is a string that identifies the value. The third input, value, is the value you want to store.

To retrieve application data, use the getappdata function:

data = getappdata(obj,name);
The component, obj, must be the component object containing the data. The second input, name, must match the string you used to store the data. Unlike the UserData property, which only holds only one variable, you can use setappdata to store multiple variables.

Share Application Data in UIs Created Programmatically

This UI uses application data to share two values. To see how it works, copy and paste this code into an editor and run it.

function my_slider()
hfig = figure();
setappdata(hfig,'slidervalue',0);
setappdata(hfig,'difference',1);

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);
	% For R2014a and earlier: 
	% maxval = get(hObject,'Max');  
	% currval = get(hObject,'Value');  
	% diffMax = maxval - currval;   
	% parentfig = get(hObject,'Parent');  
	% setappdata(parentfig,'slidervalue',currval); 
	% setappdata(parentfig,'difference',diffMax); 
end

function button_callback(hObject,eventdata)
	currentval = getappdata(hObject.Parent,'slidervalue');
	diffval = getappdata(hObject.Parent,'difference');
	% For R2014a and earlier:
	% parentfig = get(hObject,'Parent');
	% currentval = getappdata(parentfig,'slidervalue');
	% diffval = getappdata(parentfig,'difference');

	display([currentval diffval]);
end
When the user moves the slider, the slider_callback function calculates diffMax. Then, it uses these commands to modify the application data:

  • setappdata(hObject.Parent,'slidervalue',hObject.Value) stores the current slider value in the figure using the name, 'slidervalue'. In this case, hObject.Parent is the figure.

  • setappdata(parentfig,'difference',diffMax) stores diffMax in the figure using the name, 'difference'.

When the user clicks the push button, the button_callback function retrieves the data using these commands:

  • currentval = getappdata(hObject.Parent,'slidervalue') retrieves the current slider value from the figure. In this case, hObject.Parent is the figure.

  • diffval = getappdata(hObject.Parent,'difference') retrieve the difference value from the figure.

Share Application Data in GUIDE UIs

To set up a GUIDE UI for sharing application data, perform these steps:

  1. In the Command Window, type guide.

  2. In the GUIDE Quick Start dialog box, select Blank GUI (Default). Then, click OK.

  3. Display the names of the UI components in the component palette:

    1. Select File > Preferences > GUIDE.

    2. Select Show names in component palette.

    3. Click OK.

  4. Select the push button tool from the component palette at the left side of the Layout Editor and drag it into the layout area.

  5. Select the slider tool from the component palette at the left side of the Layout Editor and drag it into the layout area.

  6. Select File > Save. Save the UI as myslider.fig. MATLAB opens the code file in the Editor.

  7. Set the initial value of the application data in the opening function, myslider_OpeningFcn. This function executes just before the UI is visible to users. In myslider_OpeningFcn, insert these commands immediately after the command, handles.output = hObject.

    setappdata(handles.figure1,'slidervalue',0); 
    setappdata(handles.figure1,'difference',1);
    After you add the commands, myslider_OpeningFcn looks like this.
    function myslider_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 junk (see VARARGIN)
    
    % Choose default command line output for junk
    handles.output = hObject;
    setappdata(handles.figure1,'slidervalue',0); 
    setappdata(handles.figure1,'difference',1);
    
    % Update handles structure
    guidata(hObject, handles);
    
    % UIWAIT makes junk wait for user response (see UIRESUME)
    % uiwait(handles.figure1);
    
    Notice that handles is an input argument to myslider_OpeningFcn. The handles variable is a structure that contains all the components in the UI. Each field in this structure corresponds to a separate component. Each field name matches the Tag property of the corresponding component. In this case, handles.figure1 is the figure object. Thus, setappdata can use this figure object to store the data.

  8. Add code to the slider callback for changing the data. Add these commands to the end of the function, slider1_Callback.

    maxval = get(hObject,'Max');  
    currval = get(hObject,'Value');  
    diffMax = maxval - currval;   
    % Store application data
    setappdata(handles.figure1,'slidervalue',currval); 
    setappdata(handles.figure1,'difference',diffMax);
    After you add the commands, slider1_Callback looks like this.
    function slider1_Callback(hObject, eventdata, handles)
    % hObject    handle to slider1 (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    
    % Hints: get(hObject,'Value') returns position of slider
    %        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
    maxval = get(hObject,'Max');  
    currval = get(hObject,'Value');  
    diffMax = maxval - currval;   
    % Store application data
    setappdata(handles.figure1,'slidervalue',currval); 
    setappdata(handles.figure1,'difference',diffMax);
    This callback function has access to the handles structure, so the setappdata commands store the data in handles.figure1.

  9. Add code to the push button callback for retrieving the data. Add these commands to the end of the function, pushbutton1_Callback.

    % Retrieve application data
    currentval = getappdata(handles.figure1,'slidervalue');
    diffval = getappdata(handles.figure1,'difference');
    display([currentval diffval]);
    After you add the commands, pushbutton1_Callback looks like this.
    % --- Executes on button press in pushbutton1.
    function pushbutton1_Callback(hObject, eventdata, handles)
    % hObject    handle to pushbutton1 (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    
    % Retrieve application data
    currentval = getappdata(handles.figure1,'slidervalue');
    diffval = getappdata(handles.figure1,'difference');
    display([currentval diffval]);
    This callback function has access to the handles structure, so the getappdata commands retrieve the data from handles.figure1.

  10. Save your code by pressing Save in the Editor Toolstrip.

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 the slider position. To see how it works, copy and paste this code into an editor and run it.

function my_slider()
	hfig = figure();
	data = struct('val',0,'diffMax',1);
	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 Difference',...
         'Callback',@button_callback);

	function slider_callback(hObject,eventdata)
		sval = hObject.Value;
		diffMax = hObject.Max - sval;
		% For R2014a and earlier:
		% sval = get(hObject,'Value');
		% maxval = get(hObject,'Max');
		% diffMax = maxval - sval;

		data.val = sval;
		data.diffMax = diffMax;
	end

	function button_callback(hObject,eventdata)
		display([data.val data.diffMax]);
	end
end
The main function defines a struct array called data. When the user moves the slider, the slider_callback function updates the val and diffMax fields of the data structure. When the end user clicks the push button, the button_callback function displays the values stored in data.

    Note:   Nested functions are not recommended for GUIDE UIs.

Store Data Using the guidata Function

The guidata function provides a way to share data with the figure window. You can store or retrieve your data in any callback through the hObject component. This means that, unlike working with UserData or application data, you do not need access to one specific component to set or query the data. Call guidata with two input arguments to store data:

guidata(object_handle,data);
The first input, object_handle, is any UI component (typically hObject). The second input, data, is the variable to store. Every time you call guidata using two input arguments, MATLAB overwrites any previously stored data. This means you can only store one variable at a time. If you want to share multiple values, then store the data as a struct array or cell array.

To retrieve data, call guidata using one input argument and one output argument:

data = guidata(object_handle);
The component you specify to store the data does not need to be the same component that you use to retrieve it.

If your data is stored as a struct array or cell array, and you want to update one element without changing the other elements, then retrieve the data and replace it with the modified array:

data = guidata(hObject);
data.myvalue = 2;
guidata(hObject,data);

Use guidata in UIs Created Programmatically

To use guidata in a programmatic UI, store the data with some initial values in the main function. Then you can retrieve and modify the data in any callback function.

The following code is a simple example of a programmatic UI that uses guidata to share a structure containing two fields. To see how it works, copy and paste this code into an editor and run it.

function my_slider()
hfig = figure();
guidata(hfig,struct('val',0,'diffMax',1));
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)
	data = guidata(hObject);
	data.val = hObject.Value;
	data.diffMax = hObject.Max - data.val;
	% For R2014a and earlier:
	% data.val = get(hObject,'Value');
	% maxval = get(hObject,'Max');
	% data.diffMax = maxval - data.val;

	guidata(hObject,data);
end

function button_callback(hObject,eventdata)
	data = guidata(hObject);
	display([data.val data.diffMax]);
end
When the user moves the slider, the slider_callback function executes these commands to retrieve and modify the stored data:

  • data = guidata(hObject) retrieves the stored data as a structure.

  • data.diffMax = maxval - data.val modifies the diffMax field in the structure.

  • guidata(hObject,data) stores the modified structure.

When the user clicks the push button, the button_callback function calls guidata to retrieve a copy of the stored structure. Then it displays the two values stored in the structure.

Use guidata in GUIDE UIs

GUIDE uses the guidata function to store a structure called handles, which contains all the UI components. MATLAB passes the handles array to every callback function. If you want to use guidata to share additional data, then add fields to the handles structure in the opening function. The opening function is a function defined near the top of your code file that has _OpeningFcn in the name.

To modify your data in a callback function, modify the handles structure, and then store it using the guidata function. This slider callback function shows how to modify and store the handles structure in a GUIDE callback function.

function slider1_Callback(hObject, eventdata,handles)
% hObject   handle to slider1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles   structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range
	handles.myvalue = 2;
	guidata(hObject,handles);
end 

To see a full example of a GUIDE UI that uses the guidata function, follow these steps to copy and examine the code.

  1. Set your current folder to one to which you have write access.

  2. Copy the example code.

    copyfile(fullfile(docroot, 'techdoc','creating_guis',...
      'examples','sliderbox_guidata.*')),...
       fileattrib('sliderbox_guidata.*', '+w');
    
  3. Display this example in the GUIDE Layout Editor:

    guide sliderbox_guidata.fig
  4. View the code in the Editor by clicking the Editor button, .

  5. Run the program by clicking the Run Figure button, .

Sharing Data Among Multiple GUIDE UIs

Example of Sharing Data Between Two UIs

To see a full-featured example that uses application data and the guidata function to share data between two separate UIs, use these steps to copy, run, and examine the code.

  1. Set your current folder to one to which you have write access.

  2. Copy the example code with this command:

    copyfile(fullfile(docroot, 'techdoc','creating_guis','examples'...
      ,'changeme*.*')),fileattrib('changeme*.*', '+w');
    
  3. Display the UIs in two GUIDE Layout Editors with these commands:

    guide changeme_main
    guide changeme_dialog

  4. View the code in the editor by clicking the Editor button, , in both Layout Editors.

  5. Run the changeme_main program by clicking Run Figure button, , in that UI's Layout Editor.

Example of Sharing Data Among Three UIs

To see a full-featured example that uses guidata and UserData data to share data among three UIs, use these steps to copy, run, and examine the code.

  1. Set your current folder to one to which you have write access.

  2. Copy the example code with this command

    copyfile(fullfile(docroot, 'techdoc','creating_guis',...
      'examples','guide*.*')),...
       fileattrib('guide*.*', '+w');
    
  3. Display the UIs in three GUIDE Layout Editors with these commands:

    guide guide_iconeditor; 
    guide guide_toolpalette; 
    guide guide_colorpalette;
  4. View the code in the editor by clicking the Editor button, , in each Layout Editor.

  5. Run the guide_iconeditor program by clicking Run Figure button, , in that UI's Layout Editor.

More About

Was this topic helpful?