MATLAB Creating Graphical User Interfaces

(ff) #1

'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.


NoteNested functions are not recommended for GUIDE apps.


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 get 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:


Share Data Among Callbacks
Free download pdf