MATLAB GUI (Graphical User Interface) Tutorial for Beginners
23 Oct 2007 Quan Quach 65 comments 55249 views
Writing the code for the GUI
MATLAB automatically generates an .m file to go along with the figure that you just put together. The .m file is where we attach the appropriate code to the callback of each component. For the purposes of this tutorial, we are primarily concerned only with the callback functions. You don’t have to worry about any of the other function types.
-
Open up the .m file that was automatically generated when you saved your GUI. In the MATLAB editor, click on the
icon, which will bring up a list of the functions within the .m file. Select input1_editText_Callback.
-
The cursor should take you to the following code block:
function input1_editText_Callback(hObject, eventdata, handles) % hObject handle to input1_editText (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 input1_editText as text % str2double(get(hObject,'String')) returns contents of input1_editText as a double
Add the following code to the bottom of that code block:
%store the contents of input1_editText as a string. if the string %is not a number then input will be empty input = str2num(get(hObject,'String')); %checks to see if input is empty. if so, default input1_editText to zero if (isempty(input)) set(hObject,'String','0') end guidata(hObject, handles);
This piece of code simply makes sure that the input is well defined. We don’t want the user to put in inputs that aren’t numbers! The last line of code tells the gui to update the handles structure after the callback is complete. The handles stores all the relevant data related to the GUI. This topic will be discussed in depth in a different tutorial. For now, you should take it at face value that it’s a good idea to end each callback function with
guidata(hObject, handles);so that the handles are always updated after each callback. This can save you from potential headaches later on. -
Add the same block of code to input2_editText_Callback.
-
Now we need to edit the add_pushbutton_Callback. Click on the
icon and select add_pushbutton_Callback. The following code block is what you should see in the .m file.% --- Executes on button press in add_pushbutton. function add_pushbutton_Callback(hObject, eventdata, handles) % hObject handle to add_pushbutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)
Here is the code that we will add to this callback:
a = get(handles.input1_editText,'String'); b = get(handles.input2_editText,'String'); % a and b are variables of Strings type, and need to be converted % to variables of Number type before they can be added together total = str2num(a) + str2num(b); c = num2str(total); % need to convert the answer back into String type to display it set(handles.answer_staticText,'String',c); guidata(hObject, handles);
-
Let’s discuss how the code we just added works:
a = get(handles.input1_editText,'String'); b = get(handles.input2_editText,'String');
The two lines of code above take the strings within the Edit Text components, and stores them into the variables a and b. Since they are variables of String type, and not Number type, we cannot simply add them together. Thus, we must convert a and b to Number type before MATLAB can add them together.
-
We can convert variables of String type to Number type using the MATLAB command
str2num(String argument). Similarly, we can do the opposite usingnum2str(Number argument). The following line of code is used to add the two inputs together.total= (str2num(a) + str2num(b));
The next line of code converts the sum variable to String type and stores it into the variable c.
c = num2str(total);
The reason we convert the final answer back into String type is because the Static Text component does not display variables of Number type. If you did not convert it back into a String type, the GUI would run into an error when it tries to display the answer.
-
Now we just need to send the sum of the two inputs to the answer box that we created. This is done using the following line of code. This line of code populates the Static Text component with the variable c.
set(handles.answer_staticText,'String',c);
The last line of code updates the handles structures as was previously mentioned.
guidata(hObject, handles);
Congratulations, we’re finished coding the GUI. Don’t forget to save your m-file. It is now time to launch the GUI!
-
If you don’t want MATLAB to automatically generate all those comments for each of the callbacks, there is a way to disable this feature. From the GUI editor, go to File, then to Preferences.

65 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!