MATLAB GUI Tutorial - Sharing Data among Callbacks and Sub Functions
14 Nov 2007 Quan Quach 58 comments 12,229 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.
58 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!
Great tutorials - clear and easy to understand!
I’m trying to record a user’s interaction with a GUI. For instance, how many times did the person press a certain button? Is there a simple way to pass a variable back to the Matlab workspace?
Thanks!
-Keith
Hello
first of all, thanks alot for all the great tutorials. they absolutly saved me.
second, i encountered a problem i cant fix on my own. im using the handles. for some of my variables since i need to use them in different callbacks. in one of the calaculation, i get the OUT OF MEMORY message. at first, i thought it has something to do with the memory. but when i ran my original code (the one the does not use GUI) there was no problem.
is it possible that using GUI makes memory problems?
is it possbile that when im making my variables global they take much more memory space?
what can be done inorder to solve this problem?
thanks
Boaz
Boaz,
Can’t say that I know what your problem is exactly, but I would try to NOT use global variables unless you have too. Instead, try storing things in the GUI handles.
It’s entirely possible that the way you have coded the GUI could lead to memory problems, but I would think that if the script runs fine outside the GUI, it should be able to run fine within it.
Quan
Hi I have a small problem, Please help me.
I am working on 3 GUI windows, I have variables declared in the 1st GUI with the value assigned to it. How do I use the same variables with the values on the rest of the GUI’s?
Thank you
Dear Quan,
I followed your instructions on how to built the GUI.
I am trying to build a GUI on image compression technique only the encoding part and to produce a vector.
But the thing is i can’t seem to figure out the suitable variable for my function which i got from a book (image processing in MATLAB by Gonzales) to compress an image to jpeg2000.
Th function is somehow like:
function image= im2jpg2k (x, n, q)
i can’t seem to figure out what the variables represent.
I you are familiar with the code, could u please help me….
PLEASE PLEASE
Thank in advance…
Thanks a lot,
Great tutorials,This is what I need
Hi Quan,
Your tutorials are so clear! Thanks a lot. I am creating a GUI in MATLAB for one my projects at school, and your tutorials helped me a lot to understand how MATLAB GUIs work.
I have tried this tutorial and declared a global variable and can use it in my program under callbacks. But, I want to do something else. I am using push buttons to call different m files. I am wondering if those m files and the GUI can share data (variables) and update the same value when they are called.
Thanks for all of the tutorials again, they are so helpful!
Kamer.
Hi,
i tried your tutorial, but it didn’t work with me, i have to axes and one button
i have to load pictures from file_menu_open in axes1 than i want to call the same image to show it in axes 2
that was my code in file_menu_open:
[filename,pathname] = uigetfile({’*.jpg’;'*.png’;'*.bmp’}); %selecting the file with an open dialog
img = imread(fullfile(pathname,filename)); % reading the file stored in path
axes(handles.axes3);%axes3 est l’axe courant
imshow(img);
if ~ischar(filename) %on cancel press function ischar returns 0
return;
end
and i want to call ”img” in pushbuton.
COULD YOU PLEASE HELP ME
Thanks a lot for this great tutorial!!!
Hello,
I am creating a GUI program that calculates body mass index (bmi) and i want it to classify the user in a range according to the bmi value. (e.g. if bmi is < 18 — normal, if bmi between 18 and 24 — overweight …) .
any idea how i can do that ?
Thanks !!!!!!!
Elie
Hi,
thanks for your great tuts!
I have written little .m-File, which uses some Parameters for processing.
I would like to know, how to control these parameters by i.e. a slider?
My main understanding difficulties are, how to connect the .fig-File and its .m-GUI-File with my OWN .m-File?
Do I need to break my code up and put it into the .m-GUI-File?
Thanks for any help!
sincerely
Pooya
Can anyone give me the solution,
I am doing a project in which i have script file which calls a function like example
[a b c d]=added(e,f,g)
now i want to pass the output (a,b,c,d) to static text boxes in a gui ,what can i write to make it work
Hello Quan,
Do you know how can I save data object other than ‘String’ as global variable?
Thanks a lot in advance,
[...] GUI Tutorial - Button Types and Button Group MATLAB GUI Tutorial - A Brief Introduction to handles MATLAB GUI Tutorial - Sharing Data among Callbacks and Sub Functions Video Tutorial: GUIDE Basics More GUI Tutorial Videos From Doug [...]
Hi this is kriti,
How to provide the link between the .fig ang .m file.
I have created GUI but the input values and plot are coming at the same window.
so how i can show other window for plot.
please help me….
Hey QQ
Is there any other way to pass variables through functions without declaring them as handles ? the variables are shared by the other functions .
Thanks
@ Archiea,
Funny you should mention this, there will be a post in the very near future about ‘global variables’. If you’re in a GUI, there shouldn’t be any reason to NOT use the handles structure. Let us know what you’re thinking or why you don’t want to use handles.
-Zane
I’ve found that using the save and load commands to store a variable to disk is sufficiently fast that I don’t need to use the handles structure. Don’t ask me why, I just prefer to do it this way. However, I found that storing is .dat format is WAY faster than storing in .xls.
Liam
Hello Guys,
Thanks for the tutorial!
I have a gui that i created using your tutorial. My gui has a dropdown/popup menu which has two selection options. I have configured the selections(buttons) to display when the 1st(default) popup menu is selected. However I want another(different) set of selections to be displayed on the same gui upon selection of the second popup option from the drop down. How can I do that? I appreciate your help.
Hank
Hi I’ve been having a lot of trouble using a gui to input data and then calling an m-file to process the data. For instance if I have a text box with tag text1 and a button with tag button1. If I add code such as
myfunction(get(handles.text1,’String’));
to my buttons call back, and add the following code to my m-file:
function myfunction(mystring)
disp(mystring);
I get an Error: Reference to a cleared variable mystring
I’ve also tried:
myfunction(handles);
and
disp(get(handles.text1,’String’));
and it says: Reference to a cleared variable handles
any ideas?? I’m really stumped on this one :/
Thanks
Raj,
I don’t know why’d get that error unless you use ‘clear mystring’ in your code at any point.
Have you tried calling the display command as the first line in your ‘myfunction’ to check if that works?
One idea, which I’m not hopeful for but still might work, is to pull the handles.text1 string value into a variable before sending that to your myfunction.
Something like:
Let me know how it turns out,
Zane
Zane you made me double check my code and indeed there was a clear command. I’m such a rookie
I have a question. I have a GUI with two pushbuttons, “start” and “stop” and an edit box which I display the value of “a”. I have a function in Matlab which reads “a” from a sensor: readA.m. I want to start displaying “a” in my GUI when I push the “start” button and constantly update its value in the edit box (like a real time display) and then stop it when I push the “stop” push button. Please help.
Thanks a lot!
Retrieving text Data from an Edit Text Component
In the project I’m working on, about a dozen variables created in one gui need to be shared among three others. I’m currently using global variables, which works just fine, but I’m looking for a more secure method. Does anyone have any advice?
Never mind. Found out about getappdata. Thanks!
I want to create a square box as field, with a point representing a 2D walker. i want the point to be moving randonly in the field. can someone give me an idea about how to i can make this please. Many thanks
I am doing the Interface for my code with the GUI and i need help for this problem:
i want to do a Stop push button to stop just the execution of the program but not to close the matlab
please help and please if you can send me the answer at my Email raby1010@yahoo.com
thank you
Raby,
Check out this tutorial here:
http://blinkdagger.com/matlab/matlab-gui-tutorial-how-to-stop-a-long-running-function/