Support Articles
Graphics
Storing Data in a Gui
It is often necessary to store data in your GUI and access this data from different components in the GUI. For example you may have a "Load" push button that allows you to load an Excel spreadsheet which contains data you need to analyse. Once the data is loaded you need to store it somewhere until the "Plot" button is clicked. When "Plot" is clicked you need to retrieve the data and plot it in an axes in your GUI.

The call-back code for the "Load" push button needs to have a line of code that stores the data for later use. Once the data has been read in you can use the setappdata function to store the data in the GUI. The code could look like this:
% --- Executes on button press in load.
function load_Callback(hObject, eventdata, handles)
% Read the data from the Excel Workbook called MyData.xls
excelData = xlsread('MyData.xls');
% Store the data
h = handles.figure1;
setappdata(h,'MyExcelData',excelData)
We can use the handles structure which is passed to the callback to reference all the different components in the GUI. This particular handles structure has the following fields:
handles =
figure1: 323.0011
plot: 169.0016
load: 329.0011
axes1: 324.0011
output: 323.0011
We can set the application data for any of the objects referenced in the handles structure. The example sets the application data of the figure to be the Excel data. This data has now been stored in the GUI. Note that the data could have been stored in any of the objects referenced in the handles structure.
At a later time the "Plot" button gets clicked. We now want to retrieve the data and plot it. The getappdata function allows us to retrieve data stored by setappdata. The code could look as follows:
% --- Executes on button press in plot.
function plot_Callback(hObject, eventdata, handles)
h = handles.figure1;
excelData= getappdata(h,'MyExcelData');
plot(excelData)
Once again we find the reference to the figure by accessing the handles structure. We pass this reference to getappdata in h so that getappdata knows where the data is stored. We also tell getappdata what the name of the data is - MyExcelData. getappdata returns the data and stores it in the excelData variable. The data can then be plotted. Note that you could retrieve data in the same way from any other object callback.
MATLAB documentation background: MATLAB/Creating Graphical User Interfaces. Also type doc setappdata and doc getappdata at the command line for more information.