MATLAB GUI (Graphical User Interface) Tutorial for Beginners
23 Oct 2007 Quan Quach 71 comments 70689 views
Creating the Visual Aspect of the GUI: Part 1
-
For the adder GUI, we will need the following components
-
Two Edit Text components -
Three Static Text component -
One Pushbutton component
Add in all these components to the GUI by clicking on the icon and placing it onto the grid. At this point, your GUI should look similar to the figure below :
-
-
Next, its time to edit the properties of these components. Let’s start with the static text. Double click one of the Static Text components. You should see the following table appear. It is called the Property Inspector and allows you to modify the properties of a component.
-
We’re interested in changing the String parameter. Go ahead and edit this text to
+.

Let’s also change the font size from
8to20.

After modifying these properties, the component may not be fully visible on the GUI editor. This can be fixed if you resize the component, i.e. use your mouse cursor and stretch the component to make it larger.
-
Now, do the same for the next Static Text component, but instead of changing the String parameter to
+, change it to=. -
For the third Static Text component, change the String parameter to whatever you want as the title to your GUI. I kept it simple and named it
MyAdderGUI. You can also experiment around with the different font options as well. -
For the final Static Text component, we want to set the String Parameter to
0. In addition, we want to modify the Tag parameter for this component. The Tag parameter is basically the variable name of this component. Let’s call itanswer_staticText. This component will be used to display our answer, as you have probably already have guessed.
-
So now, you should have something that looks like the following:
Creating the Visual Aspect of the GUI: Part 2
-
Next, lets modify the Edit Text components. Double click on the first Edit Text component. We want to set the String parameter to
0and we also want to change the Tag parameter toinput1_editText, as shown below. This component will store the first of two numbers that will be added together.
-
For the second Edit Text component, set the String parameter to
0BUT set the Tag parameterinput2_editText. This component will store the second of two numbers that will be added together. -
Finally, we need to modify the pushbutton component. Change the String parameter to
Add!and change the Tag parameter toadd_pushbutton. Pushing this button will display the sum of the two input numbers.
-
So now, you should have something like this:

Rearrange your components accordingly. You should have something like this when you are done:
-
Now, save your GUI under any file name you please. I chose to name mine
myAdder. When you save this file, MATLAB automatically generates two files: myAdder.fig and myAdder.m. The .fig file contains the graphics of your interface. The .m file contains all the code for the GUI.
71 Responses to “MATLAB GUI (Graphical User Interface) Tutorial for Beginners”
Leave a Reply
Include MATLAB code in your comment by doing the following:
<pre lang="MATLAB">
%insert code here
</pre>

Thanks for the tutorial - its nice and clear
Extremely useful. Can you add a further tutorial on how to plot data in a set of axes in the GUI?
You can find the tutorial on plotting data to a set of axes here.
You can find a list of matlab tutorials here.
First of all, I greatly appreciate these tutorials. I have found the Matlab documentation simply unreadable on the subject of GUIs, and your approach with simple examples and easily modified code is perfect.
I was having some success with KeyPressFcn to make a graph with live keyboard input. Is there any way to integrate this into a graph in a GUI? Or alternatively, have a GUI running simultaneously with a live figure responding to KeyPressFcn?
Hello Fred,
I’m not sure if I’m understanding your question exactly, but I’ll try to answer it anyways.
If you look here, it’ll show you how to enter the command line mode so that you can modify any of the GUI’s components in real time, including the axes.
But I think you may be asking something different. Are you asking if there is a way to press a particular key, say “e”, and have it populate the axes on a GUI with a plot? I’d love to help, so if you can clarify your question, I will be in better shape to answer!
Quan
Hi!,
First of all, myAdder GUI tutorial very useful for beginner like me. but I have a question, is it possible to send let say; sine wave plot from one GUI window to another GUI window via UDP IP connection (using same computer)?
thanks,
zuri
Hello Quan,
Great tutorial, loved it!
I’m having a problem similar to Fred’s here (I think). I am trying to create a GUI that displays an image, and a pointer (little cross or whatever) to a current point (x,y). I want the cursor position to respond to key strokes (arrows), and various shortcuts (say ‘Ctrl+F’ for toggling a filter, ‘r’ for refresh, etc.).
I know how to implement the movement of the cursor on the image, but don’t know how to trigger it with the keystrokes.
Regards,
Gil
Zuri:
I’m a little confused on what you’re trying to accomplish, if you can elaborate then perhaps I might have an answer.
Gil:
I emailed you some code that I developed to explain this. I will probably turn this into a tutorial in the immediate future
See also:
http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=12122&objectType=FILE
Diego
Very useful. Thanks
Would you please provide the pdf file of the tutorial so it can be printed?
Hello Vahid,
This is something that we are currently working on and hope to have available in the near future. But for now, we don’t have this capability.
Simple but very useful! Thanks a lot.I am a beginner!
hello friends
i am ravi chaudhary . i done the project in fingerprint recognition in matlab. this gui tutorial help me to creating the framework of my project. thank u very much.
if anybody help me for creating source code for my project .please contact us in my
email (ravikumar_l7i@rediffmail.com)or (ravikumar_l7@yahoo.co.in)
realy nice topic i wonder if u can provide more of this
thanx alot
thanks to teach a simple GUI but i wonderful to know how to make analysis of buried optical waveguide channel using finite difference method using gui…
thanks for the feedback guys. if you click on the “matlab” tap at the top of the page, you will see a list of tutorials
or you can click here
Its realy amazed me with simplicity u xplained the GUI customsn…
its gr8 help 4 me…thx
I get an idea about gui….thanks for it…..
Can you explain how we can create a button for browsing an image for doing further process.where will be this readed image stored.whether this image can be seened.pls give the .m codes.
pls mail to my email ID
Hello Diego Barragán
Your tutorial is really useful, but I have a one question, do you have it in English?
Thanks
Lukasz
Thanks a lot guys. This made it all much clearer than the guys from Mathworks.
Hi - I am very new to Matlab (7.0) and climbimg the steep learning curve. I contructed your Gui and works fine and I think I understand the basic parts of your GUI code. I think it was nicely put together and very understandable.
Two questions though:
1) Your first added code block, ‘input = str2num(get(hObject,’String’));’ shows the variable ‘input’ and ’str2num(get’ in blue type. My editor shows these in black type ?? I have looked at the preference settings but cannot change this - but the code works and no errors. I think your screen shot more clearly defines the variable name by its blue color - any ideas?
2) I am quite confused on the ‘handles’ versus ‘hObject’ - Am I right in thinking ‘handles’ are for data being sent somewhere else and ‘hObject’ for data being received? - I am still trying to understand terminology and syntax.
Anyway - tks for you time - guys like you make it easier for guys like me!
Regards
Hi Dave,
1) The coloring scheme is a little bit off due to the wordpress plugin that I use.
2) The handles structures contain’s all the information about all of the GUI’s objects. hObject on the other hand, is the active object from which the callback is called.
So for example, if I pressed the “add” button, hObject in this case is the “add” button object.
Another example. When I input a number into the left edit text field, hObject is the edit text object.
There are a bunch of other tutorials that you can find on this website. I recommend taking a look at this one for a better understanding:
http://www.blinkdagger.com/matlab/matlab-gui-tutorial-a-brief-introduction-to-handles
Quan, thanks you so much for your quick reply. I will continue with your tutorials as you suggest.
Excellent and clear
work
Dave
Hi my friend.
Nice work , and very thank’s to you disponibility to make this tutorials.
I spend a few hours to make some things that you have here in your site, now i can found and i can see that i’m a good way.
But i have a little thing that i want to make better, so i have a edit text box where i write the 3 digits of a IP address(0…255), so my ideia is to make a limit os 3 chars on this edit text box.
I used the KeyPressFcn to count a number of pressed keys and compare it to 0..9 if is backspace or delete e decraise one number of this count.
After when i will read the data of all edit boxs i compare the text of the edit box with 0…255 and if is a letter os >255 o put ‘0′.
But also with this things isn’t perfect.
I search a lot in help of matlab, and also in internet, but i can’t found any info to make something like this.
Now how i have this i’m satisfied, but if i can make better i will more happy
So if you can give me any trick or any ideia, or any link to internet i will very appreciated.
Very tahnk’s to your pacience.
String regards,
Hugo
Hello Hugo,
I’m not quite sure how to do this off the top of my head. I’ll have to look into it. I’ll let you know if I find anything.
Quan
hello Hugo,
I could find this link very useful. The explanation was done in a very lucid manner. Thank you!
San
how we do linear regression using GUI
how to display the equation or model??
help me…
i’ve tried the tutorial step-by-step but i got error. i still got error even i’ve rewrite and corrected the code twice. then i tried to run the source code provided at this page and when i run it, still got the same error.now i’m really confuse. here the error i got when i run the source code download from this page.
??? uiopen(’C:\Documents and Settings\F3\My Documents\ani’s fyp\MATLAB\GUI\MATLAB_GUI_Tutorial for beginners(blinkdagger)-troubleshooting\myAdder.m’,1)
|
Error: Unexpected MATLAB expression.
??? Attempt to reference field of non-structure array.
Error in ==> myAdder>add_pushbutton_Callback at 134
a = get(handles.input1_editText,’String’);
Error in ==> gui_mainfcn at 95
feval(varargin{:});
Error in ==> myAdder at 42
gui_mainfcn(gui_State, varargin{:});
??? Error using ==> myAdder(’add_pushbutton_Callback’,gcbo,[],guidata(gcbo))
Attempt to reference field of non-structure array.
??? Error while evaluating uicontrol Callback
??? Attempt to reference field of non-structure array.
Error in ==> myAdder>add_pushbutton_Callback at 134
a = get(handles.input1_editText,’String’);
Error in ==> gui_mainfcn at 95
feval(varargin{:});
Error in ==> myAdder at 42
gui_mainfcn(gui_State, varargin{:});
??? Error using ==> myAdder(’add_pushbutton_Callback’,gcbo,[],guidata(gcbo))
Attempt to reference field of non-structure array.
??? Error while evaluating uicontrol Callback
>>
can u explain to me
p/s:sori for my english
meeb
download the source files. place them into a directory.
make sure the matlab current directory is the same as above
at the command prompt,
type:
Please give that a try
Thank you very much for the tutorial. From now on, I am ready to make GUI on matlab..
But, I would like to ask you some question.
How to make a GUI that connects to simulink (*.mdl)?
It’s like if you want to make GUI to take the data (input), and do the process in simulink.
How to do that?
Thank you very much..
Regards
Pradipta,
Try this tutorial:
http://www.blinkdagger.com/matlab/matlab-gui-tutorial-integrating-simulink-model-into-a-gui
OMG thank you for this tutorial! It’s really a lifesaver!
good tutorial. I am trying to create a GUI which differentiates a function so input is going to be a function of time or just a number, what will be code for converting string to function and how to use it. Pls help. The output will also be a function or a number.
Thanks,
Regards
Suri
gostei do tutorial , achei simples e bem pratico.
i enjoyed the tutorial , it is easer to use .thanks
[...] 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 and an understanding on how data is shared among callbacks is highly [...]
Hi,
in my code i have the following:
[time,number,pressure,raininput] = textread(’rain.txt’,'%s %d %f %f’,'delimiter’,',’,'headerlines’,4);
my question is how do i get the user to view the array time, and from that select the range they require? (preferably in listbox- so i can use for a gui plot)
e.g they would only require the data from the 5th row til the end. ( however they shouldn’t see the row no,but only the date)
I have’nt clue if this is even possible.
any help would be really appreciated.
{brilliant tutorials by the way - you should think about publishing a book,I’ve got 5,but yours is the easiest to understand!}
I have to cerat a GUI project for finding the resistance value from color code.Therefore we have 4 panels in which we have to insert radio buttons.one block for finding resistance value & one for closing the window.So,suggest me programme for it along with callback functions of radio buttons.
its nice n comprehensive
nice tutorial..may i ask that is there any way that can limit the length of numbers which user can input ?
may i know why i cant prevent user to key in other thing than number? I also cant open the source file downloaded? is this because i using Matlab 6 rather than 7?
Nice. One of the first GUI tutorials I’ve seen that wasn’t too simple, or too advanced. A large amount of MATLAB users don’t code with GUI’s because the process was never clearly explained to them. This tutuorial is simple and CLEAR.
Jim,
Thanks for the positive feedback!!
Quan
great work sir.. now i got a hope of completing my project!!!
Hi Quan,
Brilliant website, thanks very much.
If I was to create a clear pushbutton which resets the value displayed in the static text;what code would I write under the pushbutton function?
thanks
Jamal:
set(handles.answer_staticText,’String’,'Insert Default Static Text Here’);
Does anyone know how I can make the editText so that when the user types, it automatically goes into the editText box (i.e., the user doesn’t have to click in the box in order to type their input).
Thanks.
thanks for your help.
i could find very good information in your site
Hi. I’ve noticed that MATLAB truncates values when setting edit or static text boxes. Is there anyway of avoiding or disabling this?
Thanks
it’s nice to know about gui in MATlab;
easy & comfortable to study
thanks;)
Hi,
I have what is probably a very simple question but I just can’t find the answer:
How do I save my GUI as a jpeg so that I can use it in a report? (I’m working on a mac)
Thanks
Roisin
I have a problem to build up a simple GUI with a context graph y = a sin(x) where ‘a’ can be change by user with an edit box …
However, there is an error when using str2num, the warning that is “Requires string or character array input”
even I copy the example in the above, the same error shown in using str2num.
Please help me to solve the problem … I am the beginner of using GUI, it suffers me a lot .
hi
i have following error in my gui code.please help me:
??? Reference to non-existent field
with regards
Vinay
Thank you so much!!! It’s very helpful ^-^
danke meister für die hilfe
thanks man for your help
hi
thank u so much . it’s very useful.
Hi salute to you…No one make this much easier GUI MATLAB tutorial
Thank you for all your tutorials.
They allow everyone to start developing GUIs very very fast while trying to understand what’s happening behind and learn.
Your tutorial is very helpfull but I can’t do what I need with my GUI.
Breefly:
I need to load a signal (this is the main part of the problem) with a pusbutton. This signal consist on a matrix with n rows and m columns,then I want to plot each row with another pushbutton. And finaly a want to plot the diffrence between any combination of two rows.
The code is the following:
I will appreciate any kind of information you can send me.
Yours sincerally
Lorena
Thank you very much for this nice tutorial. I will be looking forward to see the following tutorials.
I hope other tutorials are also very easy to understand.
Simple and usefull tutorial.
Thanks
Hey, this may be a beginner question, but how do I call my GUI from a separate *.m file? Say I have file(a).m, file(b).m, and file(b).fig. How do I call my file(b) GUI from file(a).m? I’ve tried a few ways, and they call the GUI successfully, but none of the buttons or controls work. I get the following error:
??? Error while evaluating uicontrol Callback
Thanks.
Ben,
Make sure all the files above are located in the same directory. Give that a try!
Quan
Thanks, that worked. But, now what if I want the files to be in different directories?
Use the addpath command in the opening function of your main gui.
The addpath command will add a path to the list of MATLAB paths and enable you to run scripts/guis from a different path other than the current matlab directory.
Quan
Thanks, that worked well!
Hi
love the tutorials. they’re great. i was wondering if you could help me. i want to read in an input from a mirochip using a serial cable (DB9) and display that on the screen. Believe it or not, I have no idea how to read in the input, nor how to set up the cable. but what i am most concerned with is how do I use a GUI to display an external input on the screen????
This is the best tour for GUI I have ever seen. Thanks a lot!
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 ,
This tutorial is of great help for me , i did create my own GUI with 2 push buttons and two text fields which take input for my second program
I cannot figure outut
a)I want to run my 2nd matlab program with the input given in the text fields on mouse click on the push button created.
Thanks in advance.
The code for my GUI is
function varargout = samplegui1(varargin) % SAMPLEGUI1 M-file for samplegui1.fig % SAMPLEGUI1, by itself, creates a new SAMPLEGUI1 or raises the existing % singleton*. % % H = SAMPLEGUI1 returns the handle to a new SAMPLEGUI1 or the handle to % the existing singleton*. % % SAMPLEGUI1('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in SAMPLEGUI1.M with the given input arguments. % % SAMPLEGUI1('Property','Value',...) creates a new SAMPLEGUI1 or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before samplegui1_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to samplegui1_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help samplegui1 % Last Modified by GUIDE v2.5 12-Sep-2008 20:08:16 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @samplegui1_OpeningFcn, ... 'gui_OutputFcn', @samplegui1_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before samplegui1 is made visible. function samplegui1_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to samplegui1 (see VARARGIN) % Choose default command line output for samplegui1 handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes samplegui1 wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = samplegui1_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function edit1_Callback(hObject, eventdata, handles) % hObject handle to edit1 (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 edit1 as text % str2double(get(hObject,'String')) returns contents of edit1 as a double % --- Executes during object creation, after setting all properties. function edit1_CreateFcn(hObject, eventdata, handles) % hObject handle to edit1 (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 function edit2_Callback(hObject, eventdata, handles) % hObject handle to edit2 (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 edit2 as text % str2double(get(hObject,'String')) returns contents of edit2 as a double % --- Executes during object creation, after setting all properties. function edit2_CreateFcn(hObject, eventdata, handles) % hObject handle to edit2 (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 % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function Untitled_1_Callback(hObject, eventdata, handles) % hObject handle to Untitled_1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes during object creation, after setting all properties. function figure1_CreateFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns calledIt awful
Thanks for the tutorial!
It was very useful and works perfectly!