Matlab GUI Tutorial - Sharing Data among Callbacks and Sub Functions
14 Nov 2007 Quan Quach 29 comments 8572 views
Introduction
For the majority of GUIs that you create in Matlab, you will have to be able to share data among the component callbacks. One way of accomplishing this is to use the handles structure to store that data. In this tutorial, you will learn how to do so.
This tutorial is written for those with little experience creating a Matlab GUI (Graphical User Interface). If you’re new to creating GUIs in Matlab, you should visit this tutorial first. Basic knowledge of Matlab is recommended. Matlab version 2007a is used in writing this tutorial. Both earlier versions and new versions should be compatible as well (as long as it isn’t too outdated). Let’s get started!
Sharing Data Between Callbacks
A simple example of sharing data among callbacks is to increment a numerical counter on the GUI each time ANY button on the GUI is pressed. How can this be done? This tutorial will explain how.
-
First, download the sample GUI here. Unzip the files and place them wherever you please.
-
Now, type
guideat the command prompt.
-
Choose to open the sample GUI by clicking on “Open Existing GUI”. Click on “Browse” to locate where you saved the GUI files.

-
Here is what the GUI should look like when you open it:

-
Click on the
icon on the GUI figure to bring up the accompanying .m file. -
The first thing we need to do is to define a variable that will hold the value for our numerical counter. Place the following code in handles_tutorial_OpeningFcn.
handles.buttonCounter = 0; set(handles.text1,'String','0');
Make sure you place it right before this line of code:
guidata(hObject, handles);
-
Notice that we defined the variable name as handles.buttonCounter, rather than buttonCounter. If we did not define the variable within the handles structure, then it would be considered a local variable. Being a local variable means that the variable does not exist outside of the function where it was defined. Thus we need to store it into the handles structure, so that it can be accessed and modified later in the other callbacks. So, if you want data to be available to ALL callbacks, you must store it in the handles structures.
-
Add this code to both pushbutton1_Callback and radiobutton1_Callback
handles.buttonCounter = handles.buttonCounter + 1; set(handles.text1,'String',num2str(handles.buttonCounter) ); guidata(hObject, handles); %without this line, the handles structure would not update, %and the counter would not increment.
-
Now, save the .m file and run the GUI. Try clicking on the buttons to increment the counter. Notice that the counter increments when you activate AND deactivate the radio button.

Sharing Data Between Callbacks and Sub Functions
It is good practice to make your functions modular so that your code is easily adaptable, robust, and flexible. Having said that, passing the entire handles structures to sub functions is something that I don’t recommend. But there might be a time when you need to access the entire handles within a sub function. So here goes.
function [handles] = mySubFunction(handles) %insert code here % %
This function will allow you to use the handles data within the sub function, and will also update any changes made within the sub function. You can add as many inputs and outputs as desired.
When you call this function, make sure to call it in the following manner:
[handles] = mySubFunction(handles);
This is the end of the tutorial.
29 Responses to “Matlab GUI Tutorial - Sharing Data among Callbacks and Sub Functions”
Leave a Reply
Include MATLAB code in your comment by doing the following:
<pre lang="MATLAB">
%insert code here
</pre>

great tutorials… indeed very helpful. thanks a lot
Ive just spent the last 2 hours pulling my hair out, as im one of my functions was reading in values for 2 variables, and i then later call a function (if desired) to plot a PZ map, and it matlab refused to understand that the variables where there, until i realised that they where jus local variables! I tried all sorts of handles stuff, until i found this, man you guys are the reason i might get a good grade for my final year project!!!
Hallo Quan Quach,
I’ve passed though all of your tutorials. They’re really great and helpfull. At first I would like to give a big thanks for them and a round of cyber-beer
The idea of using global variables helped me alot.
And second I would like to ask for information how to solve differential equations correctly. I founded it difficult, please help
I have to make a GUI that solves maxwell’s equations in differential form for ~1kk points and plots results in 3D graphic. It’s EM wave computing using FDTD method. Any help will be appreciated. Thanks in advance 
Hi Brinkis,
I would probably use Simulink to model the differential equation and then have the GUI incorporate the Simulink model. Unfortunately, I’m not very good with simulink.
Here’s a great tutorial on using simulink:
http://edu.levitas.net/Tutorials/Matlab/Simulink/index.html
Visit this tutorial once you complete your model!
http://www.blinkdagger.com/matlab/matlab-gui-tutorial-integrating-simulink-model-into-a-gui/2#toc-the-simulink-model
Hallo Quan Quach,
I’ve failed to found simulink for download
and my matlab 2007 don’t contain it 
After I’ve red these tutorials about simulink I’ve figured out that simulink is something like a tool for making “logical schema”.
All I need is to write a code for matlab to perform a cycle. I need matlab to describe material of each point, then solve equation to found an angle for radiation pattern refers to (the directional (angular) dependence of radiation from the antenna) and then solve 6 differential Maxwell’s equations to find the value of electromagnetical field in that point. And when everything is done - plot results in 3D diagram (points should be 2D and adding value of every point we should get 3D view).
The point I’m leading to is that I already know how this should look like in matlab, but can’t imagine how to perform it with simulink. Quan Quach, if you have any experience in writing code with differential equations, please help
any hint will be appreciated
cheers,
Hello Brinkis,
I’m very rusty with differential equations within matlab, so I won’t be of much help there. One of these days I will uncover that rust and write a tutorial on differntial equations and matlab.
Quan
Thanks for such a quick reply
And thanks for your tutorial about differential equations in advance
I’ll work on solving Partial differential equation either to have more experiance 
hello Quan Quanch,
i followed your tutorial (very good…) for creating global variables.
if i want to delete one of this, what should i do????
thanks a lot……
Hey Belo
You can type command “whos” to see the variables you have in workspace then use “clear variable name” to eliminate the specific variable
thanks Daniel,
i tried it, but it doesn’t work..
i think the problem is that the variable isn’t a ‘true’ variable but is a part of the handles structure (or so i understand…. ).
ah if you are talking about handles structure yes it would be different
use the command
rmfield(handle, ‘name’)
to remove
handle.name
thanks a lot….
that’s what i need
Hi there,
i have created two list boxes which will be the start time and end time which i want to appear as the x axis on my graph. At the moment my script refers to an array called ‘time’ as the x-axis.
I would like to be able to select the start and end time from these two list boxes and then press the graph button to produce a graph for that range.
I have no idea how to link the listbox to the array ‘time’ or how to make the script i have made refer to these dates which have been chosen.
I’m really stuck and would be grateful for any help.
many thanks
%Assinging Variables
[time,number,pressure,raininput] = textread(’staticvirginia.txt’,'%s %d %f %f’,'delimiter’,',’,'headerlines’,4);
%If statement to convert pressure into volume
case1 = (pressure = 995.7 & pressure = 1149.2);
volume = zeros(size(pressure));
volume(case1) = ((pressure(case1)-442.95)*5.365);
volume(case2) = ((pressure(case2)-749.29)*12.034);
volume(case3) = ((pressure(case3)-934.08)*22.371);
cumvol = volume;
for i = 2:length(cumvol), if cumvol(i) < cumvol(i-1) cumvol(i) = cumvol(i-1); end, end
zerovol = (cumvol - (cumvol(1,1)));
%values = 3000 * (ones(size(zerovol)));
runoff = zerovol / 3000;
cumrain = cumsum(raininput);
%5 minute rain values
cumrain5 = cumrain(1:5:end);
runoff5 = runoff(1:5:end);
%Discretised values for cumrain and runoff
d = 2:length(cumrain5);
disccumrain = (cumrain5(d)) - (cumrain5(d-1));
e = 2:length(runoff5);
discrunoff = (runoff5(e)) - (runoff5(e-1));
%Graph Plotting Information
timeplot = datenum(time, ‘”yyyy-mm-dd HH:MM:SS”‘);
timeplot5 = timeplot(3:5:end);
[AX,H1,H2] = plotyy(timeplot5,disccumrain,timeplot5,discrunoff,’bar’);
set(gcf, ‘color’, ‘white’);
set(H1,’BarWidth’,0.4,…
‘EdgeColor’,[0 0.749 0.749],…
‘FaceColor’,[0 0.749 0.749],…
‘LineStyle’,'–’)
set(H2,’BarWidth’,0.4,…
‘EdgeColor’,[0.6824 0.4667 0],…
‘FaceColor’,[0.6824 0.4667 0],…
‘LineStyle’,':’)
set(AX(2),’YLim’,[0 1])
set(AX(1),’YLim’,[0 1])
set(AX(1),’YTick’,[0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1])
set(AX(2),’YTick’,[0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1])
set(get(AX(1),’Ylabel’),’String’,'Rainfall (mm)’)
set(get(AX(2),’Ylabel’),’String’,'Surface Runoff (mm)’)
title(’Surface Runoff from green roof with rainfall comparison’);
xlabel(’Time’);
datetick(AX(1),’x',15)
datetick(AX(2),’x',15)
%datetick(AX(1),’x',’dd-mmm-yyyy HH:MM:SS’)
%datetick(AX(2),’x',’dd-mmm-yyyy HH:MM:SS’)
%datetick(AX(1),’x',13)
%datetick(AX(2),’x',13)
Hi Adam,
did you solve this problem?
assuming the listbox text is just a number for your time variable, you can read the listbox values by
xmin=str2num(get(handles.listbox1,’String’));
xmax=str2num(get(handles.listbox2,’String’));
in the plot button callback function.
Did you consider using two edit text boxes for this instead? Then you would type in your min and max values in those boxes and get those by
xmin=str2num(get(handles.edittext1,’String’));
xmax=str2num(get(handles.edittext2,’String’));
in the plot button callback function.
I would then use those values to rescale the time axis after plotting the data as before.
Dear Quan Quach,
Many THANKS for ur wonderful tutorials on MATLAB GUI.
They clarified many of my doubts quickly.
Handling the global variables is what I was looking for; this tutorial explained them very well.
Just 2 minor things:
1. In the last section: “Sharing Data Between Callbacks and Sub Functions”:
“Function” has to replaced with “function”.
It seems my matlab version might be case-sensitive or, it might be just a matter of changing some settings of the matlab;
2. Initially I have copied the “guidata(hObject, handles)” also into the sub-function and then it was not working; then I moved that line into the original call-back functions and that worked.
You may just explain about this point as well so that beginners like me won’t miss it
Once again Many THANKS for these wonderful tutorials.
Warm Regards,
Subrahmanyam Gorthi.
Dear Quan,
I am currently building GUI on image compression technique. There’s been a problem which I simply can’t overcome, I’ve tried your tutorials and it still is a problem for me.
I wanted to call & run a function from a different .m file than my GUI file.
When the GUI is executed, one of it’s pushbutton (say its ‘loadhistogram’) is supposed to load and run the image compression function (say its imagecomp.m)
what should I do here, I’ve tried the set and get, but it’s still produces an error…Can you or anyone help me with this?
Thank in advance…
Fikri
Dear Quan,
Thanks for your helpful tutorial! I believe that I have followed it accurately, but for some reason, my handles structure *still* isn’t updating correctly. Here is my basic code structure:
(in Opening Function)
handles.input = 0;
guidata(hObject,handles);
—-
(in my Input Slider callback)
new_input = get(hObject,’Value’);
handles.input = new_input;
guidata(hObject,handles);
set(handles.text6,’String’,handles.input);
—-
(in my main function, initiated by clicking the Start button — this is the Start button’s callback)
input = handles.input;
if input {has a certain value},
(execute code)
end
——
The problem:
In the Slider’s callback, the value of “input” *is* updated correctly; I display this value on the gui, and this value always matches the slider’s newest value.
BUT, in the Start button’s callback, the value of “input” is *always* 0 (its initial value as defined in the OpeningFcn); “input” never gets updated within the Start button callback, despite the fact that it is regularly updated by input to the Slider.
I suspect that the problem is that the Start button click inititates a long sequence of actions, and for some reason the new values of “input” being registered in the Slider’s callback, never “register” in the Start button’s callback.
I have tried using the UserData structure, instead, but this hasn’t worked either; I haven’t found a good reference to tell me which syntax to use…
Thanks for any suggestions!
Kate
p.s.: In the Start Button callback, the first thing I do is to update the handles structure by
guidata(hObject,handles);
However, the handles structure *doesn’t* appear to update, despite this statement…
Hi Kate,
One thing you can do is the following
Also, not sure if this will make a difference, but
If this doesn’t work, please contact us through the CONTACT form!
Good luck!
Hi, Quan,
Thanks for your suggestions! Regarding your second suggestion, for your reference, I had *already* been updating guidata() in my slider callback, but that didn’t have any effect on updating within the Start Button callback.
Your first suggestion worked! I do now get() the slider value within my Start Button callback, and now this callback uses this refreshed data! Thanks for your help!
Kate
Hi Quan.
Thanks for the guide, but I still can solve the next problem:
I have a function (file myfunction.m) which is part of a recursive algorithm; this function asks the user for a number with the input keyword (in the command line).
Now I’m building the GUI for the program, but my issue is how do I replace the input by a button press. I’ve put an edit text and a button and when the user press the button the corresponding callback function is called and I don’t know how to stop the execution of myfunction.m, wait for the user to enter number, and when he presses the button, my function continues with its execution.
I pass the entire handles object to the recursive function.
I’ve tried by adding a new field as you explain here; change its value with the button callback function, meanwhile I’m checking the change of this new field (with a while) inside my function, but the program looks like it isn’t updating the field in my function (it does in the callback function) then it doesn’t detect any change which keeps the program in an infinite loop.
thanks.
(PD: sorry for my English, I’m still learning it)
Hi Carlos,
In your callback for the button that you created you can use the following code:
Without seeing your code, I can’t be of any more help. Hope this does the trick for you!
Quan
Thanks for your answer.
I think I’ve solved my problem, but your idea didn’t work. I’ll explain it , maybe useful for someone else or you can have a better idea of my problem.
I have 2 buttons (1 for start the process and the other one to process the answer) , 1 edit text and 2 archives: recursive.m and interface.m (and interface.fig). I used a global variable “answered” initialized as 0.
interface.m has the callbacks:
function button1_Callback(hObject, eventdata, handles)
recursive(handles,…other_args…); %start the recursive process
and
function buton2_Callback(hObject, eventdata, handles)
global answered
answered=1;
in my recursive function (recursive.m):
global answered
while answered==0;
pause(0.1); %this allow the GUI to refresh,
%otherwise it’s look like hang
end
mynumber=get(handles.edit1,’String’);
answered=0; %to be able to process other answers
It was my solution but I think is not too elegant. If you can give me another idea, I will be very gracefully.
Thank you, again.
Looks good to me, nice job. You can also use drawnow or refresh I believe to update the GUI.
Quan
Hi Quan,
I am new to matlab so maybe my problem is pretty easy, I have a GUI which plots several 2d figures using command plot, basically I enter vaues to static boxes and press a push botton to obtain the corespondent graph, but when I try the same for 3d plots the figure is shown perfect as expected but in a new figure and not on the axes of the gui.
Would be very appreciate any advice.
Alfredo.
[x,y,z]=xyz_patch(theta,dth,phi,dphi,R);
patch(x,y,z,z);
set(gca,’Tag’,'ActiveAxes’);
Thanks for easy describtion on how handles are used in the entire program.
Shouldn’t “Function” keyword be function “keyword”? It is just a detail but might cause some problems…
greg, i believe you are correct. THanks! Edited the post to reflect this
Hey, that was really cool! I was stuck somewhere forever, for like 8 hours
and Now I know what to do
Thanks Quan Quach!