MATLAB Creating Graphical User Interfaces

(Barry) #1
Share Data Among Callbacks

search for a specific UI component to access your 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 a Programmatic UI


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 struct array 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',...

Free download pdf