MATLAB GUI Tutorial - A Brief Introduction to handles
13 Nov 2007 Quan Quach 40 comments 11,128 views
Introduction
In this tutorial, we will discuss what handles are and how to use the get and set commands. When dealing with a Matlab GUI, you have probably noticed the variable handles being used in the accompanying .m file. The handles structure contains all the information for each object in the .fig file of the GUI. But it can also store other information. Let’s explore a little bit more about handles.
This tutorial is written for those with some experience creating a Matlab GUI. 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 isan’t too outdated).
Handles, get, and set
-
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:

-
The handles structure contains all the information for the push button, radio button, static text, the figure itself, as well as output. So how exactly do we view and access this information? There are two ways to do this. Click on the
icon on the GUI figure to bring up the accompanying .m file. You can insert in a breakpoint by left clicking on the left side of the .m file as shown.
Or you can type in
keyboardinto the .m file, as shown below.
Both methods result in the same thing. This causes the GUI to go into command line mode, allowing you to examine and change the function’s local workspace. (Incidentally, this is a great way to debug your code!)
- Let’s use the keyboard method for this tutorial.
Type
keyboardright below pushbutton1_Callback, as shown in the figure above. -
Now, save and run the GUI. Press the pushbutton.

-
The command window should pop up and you should see the following at the command window. Notice the normal command line has been replaced with “K>>” . This just means that you’re in keyboard mode.

Handles, get, and set (cont)
-
Now, let’s take a look at the variables within the function’s workspace. Type
whosat the command prompt. This command tells you what variables are in the local workspace. Nothing too interesting.
-
Now, let’s take a look at the handles. Type
handlesat the command prompt. This command gives you more details on the handles structures. You’ll notice that each object on the GUI figure is accounted for. (figure1 is the background image that your components are placed on)
-
Lets say you wanted more details on the properties of radiobutton1. You can type
get(handles.radiobutton1)at the command prompt to get a list of all the properties of this object. This command will display all the properties of that component, similar to what you would see in the Property Inspector when you double click on this component in the GUIDE figure.
-
Let’s say you only wanted details on the String property for radiobutton1; you can type
get(handles.radiobutton1,'String')at the command prompt. Additionally, you can store this value into a variable for later use. The get command is probably used most often with Edit Text components to extract user inputs.
-
Lets say you wanted to change the String property on radiobutton1. You can do this by using
set(handles.radiobutton1,'String', 'hello world')at the command prompt.
Notice that any changes you make using the set command are instantly reflected on the GUI program (not the GUIDE figure, but the actual GUI that is running).

-
Try inserting these commands into the command line:
set(handles.radiobutton1,'String', 'The button is changed!')
set(handles.radiobutton1,'BackGroundColor',[1,.3,1])
The GUI that is running should now look like this:

-
After you’re done playing around, type
returnat the command prompt to exit keyboard mode. Next, you should erase the keyboard command that you placed in the .m file and save it. Otherwise, the GUI will keep going into keyboard mode when you push that button.
40 Responses to “MATLAB GUI Tutorial - A Brief Introduction to handles”
Leave a Reply
Include MATLAB code in your comment by doing the following:
<pre lang="MATLAB">
%insert code here
</pre>


This quick short tutorial is a clear, simple but also very informative one. Thanks. It helps me to understand handles better.
I agree with tongtong, another useful hand out. good work.
sbft jwrlkce btxewo wcef fzjyamb aghxvbtj bxfrkse
Thanks for the pointer to this tutorial - It answers my problem on handles exactly and what a smooth way of testing/debugging code.
Your tutorials are far easier to understand than the official Mathlab ones.
Regards
Dave
you are doing excellent work, thanks and please keep on
Mr. Q. Quanch
you did Excelent job to introduce handles , briefly. I have few questions ,
Q1: is it possible to use h. or H. instead of complete handle word???????
Q2: what is suitable button to use an image axis or activeX control???
more questions will be forword . if received the answer of these two
with best regards
Sikander Hayat
Sikander,
by default, you have to use the word “handles” to access the structure.
Personally, I prefer to the use the image axis to place a picture because it is more stable across the different versions of matlab.
Quan
hi,
the tutorials are really helpful. Can u plz suggest some sites which has programming for medical X-ray images?
Thas was quick and much helpful thanks
Thanks for the tutorial, useful…..
hi
tnx for teh usefull information
but i had another question,is it possible to call one of the subfunctions in gui from another function? i have a gui and in that i am calling another file and i want to plot the results in this second function but because of some problems i can not send the handle to this file,so i thought maybe i can have a function in gui and call it each time. is there any way?
tnx
Thank you for this excellent tutorial, I found it much more informative than the MATLAB documentation.
Thanks,
Matteo
excellent job, thank you a lot.
very descriptive and informative tutorial. Also, it is easy to learn because of simple description. Thank you very much for handles description.
please help me in my project it is a dtmf door lock system, you must first create a password and then you must login in the keypad created using dtmf and enter your password correctly
please help me i need to pass this on or before tuesday please guys to those who are gifted with matlab skills…. thanks please email me at lnvp_17@yahoo.com if youll help il refer you to my school mates Godbless
Hi Quan,
I’m building a GUI, so far so good until I tried to make it object oriented. Say that my GUI is in a function called gui.m, and the essential function that is going to be used by gui.m are both dct. m and tmt.m, here lies the problem, both dct.m and tmt.m produces histograms, which uses panels inside gui.m for generating the histograms. How do I deal with the coding, since it will use a handle for the panel inside the gui.m
What would you suggest me in this situation.
Regards,
Fikri
Hey
Thank you so much for creating this piece. I had been trying to understand handles for the whole day and these 5 minutes are the most useful ones.
Hello………
please i need help, i have project about ” freedom for robotics”….” arm manipulator for robotics”… please help me … i need use ” GUI MATLAB”
I’m using your example code, but when I type in “whos” the handles struct is empty!
please advise…
Hi guys,
i’m using matlab r2008b to develop a gui. I have a problem with handles property: when i use get command to extract the string in an edit text
Matlab notices
??? Error using ==> get
There is no ‘String’ property in the ‘root’ class.
If i use
i have only
CallbackObject = [2090]
CommandWindowSize = [68 22]
CurrentFigure = [2050]
Diary = off
DiaryFile = diary
Echo = off
FixedWidthFontName = Courier New
Format = short
FormatSpacing = loose
Language = it_it.windows-1252
MonitorPositions = [ (2 by 4) double array]
More = off
PointerLocation = [494 397]
PointerWindow = [0]
RecursionLimit = [500]
ScreenDepth = [32]
ScreenPixelsPerInch = [96]
ScreenSize = [1 1 1024 600]
ShowHiddenHandles = off
Units = pixels
BeingDeleted = off
ButtonDownFcn =
Children = [2050]
Clipping = on
CreateFcn =
DeleteFcn =
BusyAction = queue
HandleVisibility = on
HitTest = on
Interruptible = on
Parent = []
Selected = off
SelectionHighlight = on
Tag =
Type = root
UIContextMenu = []
UserData = []
Visible = on
string property there isn’t. Why?
Francesco
Hi Fransesco,
It looks like something is wrong with your edit text box. Your handles make it seem like you’ve accessed the matlab root which you don’t want to change (I’m guessing).
“The root is a graphics object that corresponds to the computer screen. There is only one root object and it has no parent. The children of the root object are figures.
The root object exists when you start MATLAB; you never have to create it and you cannot destroy it. Use set and get to access the root properties.”
Use get(0) in your command window to see the same handles you just listed.
I would probably delete and re-create your edit box and make sure to put your code in the: rad_Ids1_edit_Callback function
good luck,
Zane
i want to create GUI window in matlab that can be used to input data and plot
I have a question about setting handles. I’m trying to set the handles for a listbox. I can set it to show a list of cities no problem. Then I decided to add the dates the data was available as well. I wanted to list the cities followed by a tab or two and then the years. This works, but the tabs are ignored so that it looks all shoved together.
For example it looks like:
Montreal1871-2008
instead of:
Montreal 1871-2008
Is this something to do with Strings? Of course it would look cleaner with the dates in front, but that doesn’t meet the requirements. Any ideas? Maybe just whitespace instead of tabs? The server needs to be reset so I can’t test that out! Thanks!
Hiii Quan…….
Thanks man…..u r doing great job and found ur site most useful on the web regarding gui……i have a question if U plz can help me…..
I want to creat a GUI such that
1) load an image
2) apply certain enhancement algorithm by pressing a push button and display the resulted image alongside the original image on the same gui
3) similarly i apply other algorithms by pressing their push buttons and the corresponding image is replaced with the new image along side the original image.
plz answer me here or to my email ammad_059@yahoo.com
Thanksss waiting for ur reply….
[...] MATLAB GUI Tutorial - Plotting Data to Axes MATLAB 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 [...]
i m using ‘ imtool’ to crop a small portion of a large image using a simple GUI…..now i get a figure window in imtool showing only the cropped part…..can u suggest me any way to use this cropped part in another function(i want to do segmentation on the cropped part)??
also i need to mention a seed point in the cropped image so that the snake’s algorithm can be used for segmentation,,how to do it using the GUI?
sir,
i written m.file code for the machine design & i got the some plots
please tell me how can i call these m.file to GUI to disply the plots
Hello there. I’m trying to run a GUI where I use the projectile formula to calcuate the users input and then plot the projectile in the GUI interface for the entire flight time. Setting up and labeling the GUI was fine, but operating it has become difficult for me. I’m using pushbuttons to calculate the max height, horizontal distance and time traveled, however when I put my code in and run my GUI, I get nothing. The following is one part that I am struggling with:
% --- Executes on button press in maxheight_b. function maxheight_b_Callback(hObject, eventdata, handles) % hObject handle to maxheight_b (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %this is my code that I put in .. h1=get(handles.selectangle_w,'Value'); %sa=str2num(h1); ---->Made this a comment, wasn't sure if they would help or not h2=get(handles.selectintvel,'Value'); %siv=str2num(h2); ---->Same as above g = 9.8; h = sa.^2*(sin(siv)).^2/(2*g); mh=num2str(h); set(handles.maxheight_w,'string',mh); guidata(hObject, handles); .. until this point. function maxheight_w_Callback(hObject, eventdata, handles) % hObject handle to maxheight_w (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of maxheight_w as text % str2double(get(hObject,'String')) returns contents of maxheight_w as a double % --- Executes during object creation, after setting all properties. function maxheight_w_CreateFcn(hObject, eventdata, handles) % hObject handle to maxheight_w (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end I'm using a listbox for the user to select their angles and initial velocity, which they are given a range I have provided for. I have named those selectangle_w and selectinvel. When I select a number from the listbox and push the button max height, my window displays nothing. I checked my tag names repeatedly but they all match up. Can you help? Also, I included the window for the maxheight button and I noticed that the m.file gives me two when I only have one window. Why is that? Very much obliged.Dear Sir
How to align text vertically in the static text box?
thanks
thank you sir.it is very good to have something so beatifullly written.
thank you sir.it is very good to have something so beatifullly written.
Hello Sir,
I have one question. Well If I use matlab GUI, how is it possible for me to create a picture on button click ? E.g if i have to show a.jpg on button click, how we can do this??
thanks
suchi
@Suchi
The general method I would use is to: create an axes tool (same size as the picture), attach a picture to it, make it invisible, then create a pushbutton that changes it to visible when you want it.
to create the picture on an axes, look here: http://blinkdagger.com/matlab/matlab-gui-tutorial-custom-background-images-and-custom-buttons
in the ‘function Your_GUI_Name_OpeningFcn’ section, include:
Create your pushbutton tool, and in the callback for that, make it visible again:
Let me know how it works!
-Zane
hi there,
I am developing a GUI wherin a series of images is to be displayed using the scroller. I am able to display the first image in an axes tool. i have read the position of this axes and then while reading the next image i m tryin to set the position at which it will b displayed to the position read. But this doesn seem to be doing what i expected it to do. on the imshow command, a new figure window is popping up in which the next image is getting displayed although the variable holding the value of the position remains unchanged.
the code is as follows:
In the initial calback to load the file:
function Load_Callback(hObject, eventdata, handles)
display(1,1);
function y = display(p,q)
global t;
y = t(:,:,p,q);
imadjust(y,[]);
global han;
han = get(handles.axes4, ‘Position’); %axes4 is the tag of the axes
set(gcf,’Position’, [han(1), han(2), han(3), han(4)]);
imshow(y,[]);
I believe the set function is setting the position of the figure window instead of setting the position at which the image should be displayed.
kindly help.
thanks,
shruti.
also in the display fuinction stated above i tried using figure(handles.axes4) butgot an error saying ‘handles’ is undefined or unidentified.
Shruti,
Your main issue seems to be confusing your axes with your figure (1 figure window can contain multiple axes). Using set(gcf,…) will change the location of the figure box. I think you want to use set(gca,…). More specific than gca would be to call the handles of the specific axes you’re trying to set.
Play around with your figure vs axes commands and I think you’ll solve most of your problems.
When debugging, you can just do get(gca) or get(gcf) and play around with the properties of each to see what happens.
Good luck,
Zane
I have a question, say I have a dot/point on a graph with coordinates as (x=2, y=3) and I want to used GET and SET to tell GUI to move the point to (x=2.5, y=3.5).How do I write the code for this. I want to put this code understand a push_button which will plot the new point. Many Thanks
Mark,
To extract the data in the axes with handle ‘Mark_axes’, try these commands:
Notice, you don’t need to use ’set’ at any point, the ‘plot’ command takes care of this.
You can do various manipulations on the data and it is possible using similar commands to manipulate lines, and even sets of lines using the ‘get(get(….’
Honestly, I didn’t know how to do this before you asked, but it was a fun exercise.
Good luck,
Zane
Can someone help me please? I have a point on a graph at (x = 0, y = 0). I want to used the timer function to move the points to these coordinates [(5, 5) (-5, 5), (5,-5), (-5,-5)] at a period of 1sec. (in each case the first number is for x and the second is y). I want to use the toggle button to start and stop the timer. Please can someone give me steps on how to do this in gui. Thanks
[...] MATLAB GUI Tutorial - Plotting Data to Axes MATLAB 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 [...]