Você está na página 1de 61

MATLAB GUI (Graphical User Interface) Tutorial for Beginners

Why use a GUI in MATLAB? The main reason GUIs are used is because it makes things
simple for the end-users of the program. If GUIs were not used, people would have to
work from the command line interface, which can be extremely difficult and frustrating.
Imagine if you had to input text commands to operate your web browser (yes, your web browser is a
GUI too!). It wouldnt be very practical would it? In this tutorial, we will create a simple GUI that will
add together two numbers, displaying the answer in a designated text field.

This tutorial is written for those with little or no experience creating a MATLAB GUI (Graphical User
Interface). Basic knowledge of MATLAB is not required, but 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 isnt too outdated). Lets get started!

Contents
Initializing GUIDE (GUI Creator)
Creating the Visual Aspect of the GUI: Part 1
Creating the Visual Aspect of the GUI: Part 2
Writing the Code for the GUI Callbacks
Launching the GUI
Troubleshooting and Potential Problems
Related Posts and Other Links
Initializing GUIDE (GUI Creator)
1. First, open up MATLAB. Go to the command window and type in guide.

2. You should see the following screen appear. Choose the first option Blank GUI (Default).

3. You should now see the following screen (or something similar depending on what version of MATLAB
you are using and what the predesignated settings are):

4. Before adding components blindly, it is good to have a rough idea about how you want the graphical
part of the GUI to look like so that itll be easier to lay it out. Below is a sample of what the finished
GUI might look like.

Creating the Visual Aspect of the GUI: Part 1
1. For the adder GUI, we will need the following components
o Two Edit Text components
o Three Static Text component
o 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 :

2. Next, its time to edit the properties of these components. Lets 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.

3. Were interested in changing the String parameter. Go ahead and edit this text to +.

Lets also change the font size from 8 to 20.

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.
4. Now, do the same for the next Static Text component, but instead of changing the String parameter to
+, change it to =.
5. 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.
6. 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. Lets call it answer_staticText. This component will be used to display our answer,
as you have probably already have guessed.

7. So now, you should have something that looks like the following:

Creating the Visual Aspect of the GUI: Part 2
1. Next, lets modify the Edit Text components. Double click on the first Edit Text component. We want to
set the String parameter to 0 and we also want to change the Tag parameter to input1_editText,
as shown below. This component will store the first of two numbers that will be added together.

2. For the second Edit Text component, set the String parameter to 0 BUT set the Tag parameter
input2_editText. This component will store the second of two numbers that will be added together.
3. Finally, we need to modify the pushbutton component. Change the String parameter to Add! and
change the Tag parameter to add_pushbutton. Pushing this button will display the sum of the two
input numbers.

4. So now, you should have something like this:

Rearrange your components accordingly. You should have something like this when you are done:

5. 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.
Writing the Code for the GUI Callbacks
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 dont have to worry
about any of the other function types.
1. 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.

2. The cursor should take you to the following code block:
3. function input1_editText_Callback(hObject, eventdata, handles)
4. % hObject handle to input1_editText (see GCBO)
5. % eventdata reserved - to be defined in a future version of MATLAB
6. % handles structure with handles and user data (see GUIDATA)
7.
8. % Hint: get(hObject,'String') returns contents of input1_editText as text
9. % str2double(get(hObject,'String')) returns contents of
10. % 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 dont want the user to put in
inputs that arent 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 its 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.
11. Add the same block of code to input2_editText_Callback.
12. 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.
13. % --- Executes on button press in add_pushbutton.
14. function add_pushbutton_Callback(hObject, eventdata, handles)
15. % hObject handle to add_pushbutton (see GCBO)
16. % eventdata reserved - to be defined in a future version of MATLAB
17. % 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);
18. Lets discuss how the code we just added works:
19. a = get(handles.input1_editText,'String');
20. 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.
21. We can convert variables of String type to Number type using the MATLAB command
str2num(String argument). Similarly, we can do the opposite using num2str(Number argument).
The following line of code is used to add the two inputs together.
22. 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.
23. 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.
24. set(handles.answer_staticText,'String',c);
The last line of code updates the handles structures as was previously mentioned.
guidata(hObject, handles);
Congratulations, were finished coding the GUI. Dont forget to save your m-file. It is now time to
launch the GUI!










MATLAB GUI Tutorial - Slider
28 Oct 2007 Quan Quach 108 comments 20,071 views
Introduction
In this Matlab GUI tutorial, you will learn how to create and use the slider component.
Sliders are useful controls for choosing a value in a range of values. Common uses are
volume controls, seekers for movie and sound files as well as color pickers. An example
of a slider is shown below.

This tutorial is written for those with little or no experience creating a Matlab GUI (Graphical User
Interface). If youre new to creating GUIs in Matlab, you should visit this tutorial first. Basic knowledge
of Matlab is not required, but 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 isnt too outdated). Lets
get started!
Create the Visual Aspect of the GUI
1. Start up Matlab, and type guide in the command line.

2. Choose to create a new GUI using the Blank GUI(Default) option.

3. Click on and add an Edit Text component to the GUI figure. Next, click on and add a Slider
component onto the GUI figure.
4. Double click the Edit Text component to bring up the Property Inspector. Change the String property
to 0, and change the Tag property to sliderValue_editText as shown in the figure below:

5. Next, lets modify the properties of the Slider component. First lets sit the Min property to 0, and the
Max property to 100. Next, change the Tag property to slider1.

6. Heres what your figure should look like after you add the components and modify them.

7. At this point, you also might want to add some Static Text components to specify the min and max
values of the slider. You can modify their text by double clicking on the component and changing the
String property. Its not required, but I highly recommend it.

8. Save your GUI wherever you please with your desired filename.
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 dont have to worry
about any of the other function types.
1. 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
slider1_Callback.

Add the following code to the function:
%obtains the slider value from the slider component
sliderValue = get(handles.slider1,'Value');

%puts the slider value into the edit text component
set(handles.slider_editText,'String', num2str(sliderValue));

% Update handles structure
guidata(hObject, handles);
2. Now, lets add the following code to the slider_editText_Callback function:
%get the string for the editText component
sliderValue = get(handles.slider_editText,'String');

%convert from string to number if possible, otherwise returns empty
sliderValue = str2num(sliderValue);

%if user inputs something is not a number, or if the input is less than 0
%or greater than 100, then the slider value defaults to 0
if (isempty(sliderValue) || sliderValue < 0 || sliderValue > 100)
set(handles.slider1,'Value',0);
set(handles.slider_editText,'String','0');
else
set(handles.slider1,'Value',sliderValue);
end
3. Save your m-file!
Run and Test the GUI
Now that weve completed both the visual and code aspects of the GUI, its time to run the GUI to
make sure it works.
1. From the m-file editor, you can click on the icon to save and run the GUI. Alternatively, from the
GUIDE editor, you can click on the to launch the GUI. The following GUI should appear once you
click the icon:

2. Now, try to put in different types of inputs to test the GUI. Any input that is not a number, less than
zero, or greater than 100 should default the slider to a value of zero.
3. And thats it. Those are the basics of using a Slider component. You can explore the other options that
the slider has to offer through the Property Inspector. For instance, you can use the SliderStep
property to customize how far you want the slider to move when you press the left and right arrow, or
when you click on the scroll bar.
This is the end of the tutorial.

MATLAB GUI Tutorial - Plotting Data to Axes
31 Oct 2007 Quan Quach 144 comments 25,632 views
Introduction
In this Matlab GUI tutorial, you will learn how to create and use the Axes component. The
Axes component allows you to display graphics, such as graphs and images on your GUI.
In this tutorial, we will create two axes on the GUI and plot some simple data onto it. In
addition, we will include a reset button to clear the axes and we will also add the
standard toolbar to allow the user to zoom, pan, and query the plot.

This tutorial is written for those with little or no experience creating a Matlab GUI (Graphical User
Interface). If youre 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 isant too outdated). Lets get started!
Create the Visual Aspect of the GUI
1. First, open up Matlab. Go to the command window and type in guide.

2. You should see the following screen appear. Choose the first option Blank GUI (Default).

3. Click on and add two Axes components to the GUI figure. Next, click on and add three
Pushbutton components onto the GUI figure.
4. Double click the Axes component to bring up the Property Inspector. Change the Tag property to
axes1, which should already be the default name. Additionally, make sure the other Axes
components Tag property is named axes2.


5. Next, lets modify the properties of the Pushbutton components. Double click on one of the Pushbutton
components. Change the String property to Plot Axes 1, and the Tag property to
plotAxes1_pushbutton, as shown below.


Similarly, double click on the next pushbutton and change the String property to Plot Axes 2 and
change the Tag property to plotAxes2_pushbutton.
Finally, double click on the final pushbutton and change the String property to Clear Axes and
change the Tag property to clearAxes_pushbutton.
6. Heres what your figure should look like after you add the components and modify them.


7. Save your GUI wherever you please with your desired filename.
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 dont have to worry
about any of the other function types.
1. 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
plot1_pushbutton_Callback.


Add the following code to the function:
%selects axes1 as the current axes, so that
%Matlab knows where to plot the data
axes(handles.axes1)

%creates a vector from 0 to 10, [0 1 2 3 . . . 10]
x = 0:10;
%creates a vector from 0 to 10, [0 1 2 3 . . . 10]
y = 0:10;

%plots the x and y data
plot(x,y);
%adds a title, x-axis description, and y-axis description
title('Axes 1');
xlabel('X data');
ylabel('Y data');
guidata(hObject, handles); %updates the handles
2. Similarly, we want to put the following code into the plot2_pushbutton_Callback:
3. %selects axes2 as the current axes, so that
4. %Matlab knows where to plot the data
5. axes(handles.axes2)
6.
7. %creates a vector from 0 to 10, [0 1 2 3 . . . 10]
8. x = 0:10;
9. %creates a vector [0 1 4 9 . . . 100]
10. y = x.^2
11.
12. %plots the x and y data
13. plot(x,y);
14. %adds a title, x-axis description, and y-axis description
15. title('Axes 2');
16. xlabel('X data');
17. ylabel('Y data');
guidata(hObject, handles); %updates the handles
18. Next, we need to add some code to the clearPlots_pushbutton_Callback:
19. %these two lines of code clears both axes
20. cla(handles.axes1,'reset')
21. cla(handles.axes2,'reset')
guidata(hObject, handles); %updates the handles
22. And finally, we need to add the following line of code to axes_tutorial_OpeningFcn:
set(hObject,'toolbar','figure');
This line of code should be placed right before:
guidata(hObject, handles);
This line of code effectively adds the standard toolbar to the GUI, allowing the user to zoom, pan,
query the plot, and more. The standard toolbar and a brief description of the icons are shown below:

23. Save your m-file!
Run and Test the GUI
Now that weve completed both the visual and code aspects of the GUI, its time to run the GUI to
make sure it works.
1. From the m-file editor, you can click on the icon to save and run the GUI. Alternatively, from the
GUIDE editor, you can click on the to launch the GUI. The following GUI should appear once you
click the icon:

2. Go ahead and try pressing all of the buttons to make sure they work. If everything was done correctly,
you should see the following plots. Also, you can use the icons that are within the red box to test out
the other functions.


3. And thats it. Those are the basics of using the Axes component. You can explore the other options
that the axes has to offer through the Property Inspector.
This is the end of the tutorial.








Matlab GUI Tutorial - Integrating Simulink Model into a GUI

Introduction
This tutorial will show you how to easily interface a Simulink Model with GUIDE using two
different methods. In this tutorial, you will learn how to pass parameters to a Simulink
model without using the set_param command and without having the Simulink Model
open (which is how the Matlab Help does it).
Since Simulink can be used to easily model a variety of systems using an intuitive block diagram
format, it would be advantageous to use it in conjunction with GUIs. Interfacing the Simulink Model
with GUIDE will makes it easier for end-users to change key parameters and to view simulations
without having to deal directly with Simulink.
This tutorial is written for those with some experience creating a Matlab GUI and with some
experience using Simulink. If youre new to creating GUIs in Matlab, you should visit this tutorial first.
Basic knowledge of Matlab is highly 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 isant too
outdated). Lets get started!
The Simulink Model
In this part of the tutorial, we will quickly go over the Simulink Model. The Simulink Model is of a
mass-spring-damper system, which is a simple 2nd order system. The following is a free body
diagram of the mass-spring-damper system.

It is assumed here that you know how to use Simulink and understand the basic theory of the mass-
spring-damper system, so I will not go into any detail on how the model was generated or how
equations were derived. If you are clueless on using Simulink, this is a good place to visit.
1. First, download the sample files provided here. Unzip the files and place them wherever you please.
The zip file includes 4 files: simulink_gui.fig, simulink_gui.m, simulateButton.m, and mass_spring.mdl.
2. The following is a diagram of the Simulink Model for the above system.

3. Notice that the Gain blocks use variables instead of number values: 1/m, c/m, and k/m. To simulate
this system from the command line, we use the sim command. Since the Simulink Model is linked
to the main workspace by default, the parameters m,c and k must be defined within the main
workspace in order for the sim command to work properly. Otherwise, an error will result. There are
ways to get around this using the command simset, and we will discuss this in the next section.
4. Thus, if the variables m,c, and k are not defined in the main workspace and we try to use a function
like the one listed below, an error would result!
5. function runSimulinkModel(m,c,k)
sim('mass_spring');
6. This can be especially troublesome if you are trying to interface your Simulink Model into a GUI
because GUIs store all their information outside from the main workspace. In the next section, we will
discuss two ways to resolve this problem.
In this part of the tutorial, we are going to code the GUI so that it can call the Simulink Model.
The GUI portion Method 1: using simset
The simset command allows you to define which workspace to run your simulink model from. By
default, the simulink model is run from is the main workspace.
1. Type guide at the command prompt.

2. Choose to open the sample GUI by clicking on Open Existing GUI. Click on Browse to locate where
you saved the GUI files.

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

4. The following is the code for the simulate_pushbutton_Callback functon.
5.

axes(handles.axes1) %set the axes
6.

m=str2num(get(handles.mass_editText,'String')); %fetch the mass value
7.

c=str2num(get(handles.damping_editText,'String')); %fetch the damping value
8.

k=str2num(get(handles.spring_editText,'String')); %fetch the spring constant
9.


10.

%configure the options so that the current
11.

%workspace is used in simulating the model
12.

options = simset('SrcWorkspace','current');
13.


14.

%the sim command simulates the simulink model
15.

%the first argument is the model name
16.

%the second argument is an array containing the start and stop time
17.

%if [] is used, then the value from within the simulink model is used
18.

%the third argument is the options configured from simset
19.

sim('mass_spring',[],options);
20.

%plot the data
21.

plot(tout,yout)
22.

xlabel('Time')
23.

ylabel('Displacement')
24.

Title('2nd Order Mass Spring System')
grid on
25. Now, we are ready to run the GUI. You should see the following GUI appear. Try inputting different
parameters and simulating the system response. Be sure the parameters are well defined (no letters,
no symbols, no negative numbers, etc) or an error will result.

The GUI portion Method 2
This method is not as elegant as the previous method, but it is how I first learned how to run simulink
models within GUIs.
1. Type guide at the command prompt.

2. Choose to open the sample GUI by clicking on Open Existing GUI. Click on Browse to locate where
you saved the GUI files.

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

4. Double click on the Simulate Button to bring up the Property Inspector. Change the Callback
property to simulateButton. Now, each time the Simulate button is pressed, the callback is
mapped to the simulateButton m-file instead of the normal callback.

5. The following is the code for simulateButton.m. This file is included in the zip folder you downloaded
earlier. Notice that this m-file is NOT in function format. Instead, all of these commands are being
executed in the main workspace area! Since all the parameters are defined in the main workspace,
when we use the sim command to simulate the model, the variables m,c,and f are defined!! This
would not have been possible if a normal callback was used.
6. %notice that this m-file is NOT a function because simulink models
7. %only allows you to use variables that are within the main workspace
8. clear all
9.
10. %make the handles structures available to the main workspace
11. h =gcf;
12. handles = guidata(h);
13.
14. %set the axes to which the data will be plotted to
15. axes(handles.axes1);
16.
17. % get the parameters from the edit text fields
18. m=str2num(get(handles.mass_editText,'String'));
19. c=str2num(get(handles.damping_editText,'String'));
20. k=str2num(get(handles.spring_editText,'String'));
21.
22. %simulate the system
23. sim('mass_spring');
24.
25.
26. %plot the data
27. plot(tout,yout)
28. xlabel('Time')
29. ylabel('Displacement')
30. Title('2nd Order Mass Spring System')
grid on
31. Now, we are ready to run the GUI. You should see the following GUI appear. Try inputting different
parameters and simulating the system response. Be sure the parameters are well defined (no letters,
no symbols, no negative numbers, etc) or an error will result.

The next section will discuss how to configure other Simulink parameters such as the sources, sinks,
time steps, simulation time, and some other things.
How to specify other Simulink Parameters through the GUI
Specifying other Simulink Parameters through the GUI is not a difficult task. In this section of the
tutorial, I will provide an example on how to do this. You can download the source files here if you do
not want to read through the tutorial. Lets say that we want to add the following capabilities to our
GUI:
set simulation time
set sample time
set the time when the unit step occurs
designate the output parameter names
1. First, lets make it so the user can specify the simulation time through the GUI. It is possible to specify
the start and stop time as an argument to the sim command.
For example, if I wanted to simulate the model for a specific period of time, I would use the following
command:
sim('mass_spring',[0 simTime]);
If no time argument is given, then the value specified within the Simulink Model is used.
Another way of doing this is through the Simulink Model itself. To do this, we need to set the
simulation time parameter to a variable. As can be seen in the image, I changed it to simTime.

2. Next, double click on the Step block. Change the Step time field to stepTime and the Sample time
field to sampleTime as shown in the image below.

3. Finally, lets change the output block. Previously, the output was called yout by default. But suppose
you want to give your output a more descriptive name, like displacement. Instead of using the Out1
sink, we would instead use the To Workspace sink. So go ahead and replace the old output sink with
the new one.

4. Finally, we need to modify the properties of the output sink that we just added. Double click on the
component and change the Variable name field to displacement and change the Save format field to
Array.

5. The Simulink model should now look like this:

6. Another thing you might want to do is to NOT limit the number of data points that result from your
simulation. You can deactivate this by going to Simulation => Configuration Parameters from the
Simulink Model.

7. Now, lets move on to the GUI changes. I wont go over each step. But all we have to do is add on
three Static Text Components and three Edit Text Components and to rename their Tag property
appropriately. I renamed the Tag property for each of the Edit Text components to:
stepTime_editText, sampleTime_editText, and simTime_editText. Heres what your GUIDE figure
should look like after you make the edits:

8. Finally, I made some minor edits to the simulate_pushbutton_Calback function.
9.

function simulate_pushbutton_Callback(hObject, eventdata, handles)
10.


11.

axes(handles.axes1)
12.

% get the parameters from the edit text fields
13.

m=str2num(get(handles.mass_editText,'String'));
14.

c=str2num(get(handles.damping_editText,'String'));
15.

k=str2num(get(handles.spring_editText,'String'));
16.

stepTime=str2num(get(handles.stepTime_editText,'String'));
17.

sampleTime=str2num(get(handles.sampleTime_editText,'String'));
18.

simTime=str2num(get(handles.simTime_editText,'String'));
19.


20.

options = simset('SrcWorkspace','current');
21.

sim('mass_spring',[],options);
22.

%plot the data
23.

plot(tout,displacement)
24.

xlabel('Time')
25.

ylabel('Displacement')
26.

title('2nd Order Mass Spring System')
grid on
27. After you make all of these changes, you can finally test and run your GUI! Try inputting in different
input parameters to test it out.

If you are unable to get your GUI/Simulink Model to work, you can download the source files here .
We encourage you explore and to play around with some of the other features within Simulink. There
are a myriad of features that were not discussed, and we hope this tutorial has given you a better idea
on how to use a GUI in conjunction with Simulink.
This is the end of the tutorial.




Matlab GUI Tutorial - Mapping a Keyboard Button to Execute a GUI
Callback
Introduction
This tutorial will teach you how to map a keyboard press to execute a GUI callback.
We will start with a basic adder GUI. Originally, the GUI adds the two numbers together
when the user clicks on the add button. We will modify the GUI so that the two
numbers will add when the user presses the enter key. For more information on
this topic, visit this post on Adding Shortcut keys / Hot keys to a GUI.

Example: Modifying the Adder GUI
1. First, download the Adder GUI source files here.
2. Next, we want to add the following line in the opening function:
3.

%we must define the KeyPressFcn for the edit text boxes or else the
4.

%enter key will not register while the edit text box is active
5.


6.

set(handles.figure1,'KeyPressFcn',@myFunction);
7.

set(handles.input1_editText,'KeyPressFcn',@myFunction);
set(handles.input2_editText,'KeyPressFcn',@myFunction);
8. Next, we want to add the following code at the end of the m-file
9.

function myFunction(src,evnt)
10.

%keyPressFcn automatically takes in two inputs
11.

%src is the object that was active when the keypress occurred
12.

%evnt stores the data for the key pressed
13.


14.

%brings in the handles structure in to the function
15.

handles = guidata(src);
16.


17.

k= evnt.Key; %k is the key that is pressed
18.


19.

if strcmp(k,'return') %if enter was pressed
20.

pause(0.01) %allows time to update
21.


22.

%define hObject as the object of the callback that we are going to
use
23.

%in this case, we are mapping the enter key to the add_pushbutton
24.

%therefore, we define hObject as the add pushbutton
25.

%this is done mostly as an error precaution
26.

hObject = handles.add_pushbutton;
27.


28.

%call the add pushbutton callback.
29.

%the middle argument is not used for this callback
30.

add_pushbutton_Callback(hObject, [], handles);
end
31. And thats it. Run the GUI and verifies that it works.
Matlab GUI - Adding a Custom Menu Bar
04 Feb 2008 Quan Quach 15 comments 4,151 views
Introduction
A menu bar can add a lot of functionality to a GUI without taking up much space. If we
used a pushbutton to assign each individual callback, then the GUI would look crowded
and confusing. The default menu bar can be added to a GUI quite easily, and looks like
this:

Unfortunately, many of the features in the default menu bar might not apply to your GUI. Thus, the
next best thing is to define your own custom menu bar. I prefer to use a custom menu bar to
lump together functions that while important, are not used often enough to warrant its own
pushbutton. Creating a custom menu bar is quite easy using GUIDE, and we shall illustrate this in
the upcoming example.
The Default Menubar
There are two different ways you can use to add the default menu bar to your GUI.
1. Add the following line of code to the opening function:
set(handles.figure1,'MenuBar','figure');
2. Double click on the background of the GUIDE figure to bring up the Property Inspector. Set the
MenuBar property to figure.

Adding your own Custom Menu Bar: A Simple Example
1. In this example, we will create a GUI that can adjust the size of the text using the menu items created
in the custom menu bar. I have provided a skeleton GUI to get you started, which you can download
here.
2. Now, type guide at the command prompt.

3. Choose to open the sample GUI by clicking on Open Existing GUI. Click on Browse to locate where
you saved the GUI files.

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

5. Next, go to Tools => Menu Editor as shown in the figure

6. You should see the following window appear. Click on the upper left icon to create a new menu.

7. Now, you can change the Label and Tag properties. I recommend you use the same names that I used
in the image below.

8. Next, we need to add menu items. Click on the second icon twice to create two new menu items.

9. Lets designate the first menu item as the option that will increase the font. Fill out the Label, Tag, and
Accelerator accordingly. Note: The accelerator is basically used as a hotkey within the GUI. This
means you can press Control + Q to execute the Callback associated with this menu item.

10. Lets do the same for the second item and make it the option that will decrease the font. After youre
done with this, press the OK button

11. Next, we need to add some code to the callbacks, which were automatically generated for us when we
configured the menu items. Go to the m-file and you should see three callbacks that were added. We
dont need any code for the fontMenu_Callback.
For the increaseFont_Callback, we want to add the following code:
currentFontSize = get(handles.blinkdagger,'FontSize');
set(handles.blinkdagger,'FontSize',currentFontSize+2);
Next, we want to add code to the decreaseFont_Callback:
currentFontSize = get(handles.blinkdagger,'FontSize');
set(handles.blinkdagger,'FontSize',currentFontSize-2);
12. Now we are ready to run the GUI. You should see the following GUI appear

13. Notice the menu that you just configured! You can either manually click on the menu items to
increase/decrease the font size, or use the accelerator to increase (control + Q) and decease (control
+ W) the font size. Go ahead and give it a try!

Default + Custom Menu Bar
If you enable the default menu bar and also define a custom menu bar, the custom menu bar will
show up at the end of the default menu bar. See the image below.

Download the Source Files
You can download the source files here.
This is the end of the tutorial.



Introduction
In this tutorial, you will learn how to save data from your GUI, and how to load it back in.
This is a useful feature when you want your GUI to remember a group of settings. In
addition, this gives you the chance to go back to previous states. The example we will
use in this tutorial involves the slider GUI that was created in the Slider Tutorial. Here is a
quick look at the finished GUI.

The Example Files and Code
1. First, download the GUI skeleton here. Unzip the files and place them wherever you please.
2. Now, type guide at the command prompt.

3. Choose to open the sample GUI by clicking on Open Existing GUI. Click on Browse to locate where
you saved the GUI files.

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

5. Click on the icon on the GUI figure to bring up the accompanying .m file.
6. Lets add some code to each of the pushbuttons. First, lets add the code for the save button.
Find the save_pushbutton_Callback and add the following code
%allow the user to specify where to save the settings file
[filename,pathname] = uiputfile('default','Save your GUI settings');

if pathname == 0 %if the user pressed cancelled, then we exit this callback
return
end
%construct the path name of the save location
saveDataName = fullfile(pathname,filename);

%saves the gui data
hgsave(saveDataName);
7. Next, we want to add the following code to the load_pushbutton_Callback:
8. %allow the user to choose which settings to load
9. [filename, pathname] = uigetfile('*.fig', 'Choose the GUI settings file to load');
10.
11. %construct the path name of the file to be loaded
12. loadDataName = fullfile(pathname,filename);
13.
14. %this is the gui that will be closed once we load the new settings
15. theCurrentGUI = gcf;
16.
17. %load the settings, which creates a new gui
18. hgload(loadDataName);
19.
20. %closes the old gui
close(theCurrentGUI);
21. You might have noticed there were more callbacks, but you can ignore those for now. Lets run the
GUI! You should see the following GUI appear when you run it:

22. Now, lets move the slider all the way to the right, like this:

23. Now, lets save the GUIs current state. Press the Save GUI Settings button. The following window
should appear, asking where to save the GUI data.

24. Next, move the slider to any arbitrary location. Now, click on the Load GUI Settings. Choose the
same file that you just saved.

25. You should see a brief flicker, and the GUI should be restored to exactly how you just saved it seconds
ago. If you moved the GUI to another location on the screen after the save, it will be sent back to the
position it was at when you saved it!
26. You probably noticed the menu on the upper left of the GUI. If you dont know how to create a custom
menu, I suggest you visit this tutorial first. Anyhow, we can go back to the m-file and add in some
code for the menu item callbacks. I prefer to use menu items sometimes because they help keep the
GUI looking clean and uncluttered.

Copy the same code from the save_pushbutton_Callback to the saveSettings_Callback.
Similarly, do the same for load_pushbutton_Callback and loadSettings_Callback.
27. Now run the GUI again, and try using the menu instead. It should work exactly the same! In addition,
you can even try the hotkeys, (Control + S) to save, and (Control + L) to load.





Matlab GUI - Using msgbox to Create a Better GUI
18 Feb 2008 Quan Quach 19 comments 5,346 views
Introduction
The msgbox command in Matlab can provide valuable information to the user of your
GUI. It can warn the user, inform the user of an error, and also provide help. In this
example, we will use a GUI (shown below) consisting of a simple edit text component.

The GUI takes in inputs between 0 to 100.
If the user tries to input a numerical value that is not within 0-100, then the GUI will spit out an error
message.

If you user tries to set the value to 100, the user will give off a warning message.

If you try to input something that is not a number, the user will get a help message.

The Example
1. First, download the GUI skeleton here. Unzip the files and place them wherever you please.
2. Now, type guide at the command prompt.

3. Choose to open the sample GUI by clicking on Open Existing GUI. Click on Browse to locate where
you saved the GUI files.

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

5. Click on the icon on the GUI figure to bring up the accompanying .m file.
6. Now, we want to add the following code to edit1_Callback.
7. input = get(handles.edit1,'String'); %get the input from the edit text field
8. input = str2num(input); %change from string to number
9.
10. if isempty(input) %if the input is not a number
11.
12. %this is the first line of the msgbox
13. msgboxText{1} = 'You have tried to input something that is NOT a number.';
14. %this is the second line
15. msgboxText{2} = 'Try an input between 0 and 100 instead.';
16.
17. %notice that msgboxText is a Cell array!
18.
19. %this command creates the actual message box
20. msgbox(msgboxText,'Input not a number', 'help');
21.
22. elseif input == 100 %if the input is exactly 100
23. msgboxText{1} = 'You have chosen the highest possible input!';
24. msgboxText{2} = 'You cannot go any higher than this or it will result in an error.';
25. msgbox(msgboxText,'Maximum input chosen', 'warn');
26.
27. elseif input < 0 || input > 100 %if the input is less than 0 or greater than 100
28. msgboxText{1} = 'You have chosen a value outside the range of 0-100!';
29. msgbox(msgboxText,'Input not allowed', 'error');
end
30. And thats it! Run the GUI to make sure that it does what you expect it too.
Other tips
The msgbox command can be replaced with the errordlg, warndlg, and helpdlg commands. Its
purely a matter of preference. For example:
msgbox('hello world', 'hello world','error');

%an equivalent command
errordlg('hello world','hello world')
















MATLAB GUI - How to Easily Share Data Between Two Separate GUIs
Introduction
Oftentimes, we need to share data between two separate GUIs. This tutorial will show
you how to do just that. While there are many ways to share data between two GUIs, this
tutorial will present the most simple method (in our opinion). Below are two simple GUIs
that were created as an example for this tutorial.
Quans GUI and Daniels GUI each take in an input. Quans GUI is able to extract the input from
Daniels GUI, and vice versa. How is this accomplished? Lets run through the example and find out.
Note: If you want to use a sub GUI to change settings parameters on a main GUI, check out this
tutorial instead!

The Example
1. First, download the GUI skeletons here. Unzip the files and place them wherever you please.
2. Now, type guide at the command prompt.

3. Choose to open the sample GUIs by clicking on Open Existing GUI. Click on Browse to locate where
you saved the GUI files.

4. The two GUIs should look like this when you open them:

5. Click on the icon on the GUI figure to bring up the accompanying .m file.
6. First, lets add the following code to pushbutton1_Callback for Quans GUI.
7.

danielFigureHandle = daniel; %stores the figure handle of Daniel's GUI here
8.


9.

%stores the GUI data from Daniel's GUI here
10.

%now we can access any of the data from Daniel's GUI!!!!
11.

danielData = guidata(danielFigureHandle);
12.


13.

%store the input text from Daniel's GUI
14.

%into the variable daniel_input
15.

daniel_input = get(danielData.editText_Daniel,'String');
16.


17.

%set the static text on Quan's GUI to match the
18.

%input text from Daniel's GUI
19.

set(handles.display_daniel_input,'String',daniel_input);
20.


21.

%notice that danielData is the structure containing the data from
Daniel's GUI
22.

%notice that handles is the structure containing data from Quan's GUI,
%which is the local GUI (i.e., the GUI that this function is running from)
23. Second, lets add the following code to pushbutton1_Callback for Daniels GUI.
24.

quanFigureHandle = quan; %stores the figure handle of Quan's GUI
here
25.


26.

%stores the GUI data from Quan's GUI here
27.

%now we can access any of the data from Quan's GUI!!!!
28.

quanData = guidata(quanFigureHandle);
29.


30.

%store the input text from Quan's GUI
31.

%into the variable quan_input
32.

quan_input = get(quanData.editText_Quan,'String');
33.


34.

%set the static text on Daniel's GUI to match the
35.

%input text from Quan's GUI
36.

set(handles.display_quan_input,'String',quan_input);
37.


38.

%notice that quanData is the structure containing the data from Quan's
GUI
39.

%notice that handles is the structure containing data from Daniel's
GUI,
%which is the local GUI (i.e., the GUI that this function is running from)
40. And thats it! Run the two GUIs simultaneously side by side. Enter in any input you choose for the two
GUIs and test it to make sure that it does what you expect it too.



Matlab - A Simple but Powerful Command: questdlg
14 Mar 2008 Quan Quach 15 comments 3,127 views
Introduction
Sometimes, the simplest of things can prove to be quite useful. I want to promote the
questdlg command within Matlab because I think its a very useful command that people
either 1) overlook, or 2) does not know that it even exists! With this command, you can
create a pop-up window that will ask you a question, and will allow you to choose one of the options.
For instance, if we use the following code, we can create a window that queries the user for their
favorite color. Go ahead and copy and paste the following code into the Matlab command prompt.
%this example comes directly from the Matlab help
ButtonName = questdlg('What is your favorite color?', ...
'Color Question', ...
'Red', 'Green', 'Blue', 'Green');

Once you click on any of the buttons, it will return the appropriate argument into the variable
ButtonName. Read the rest of this tutorial for some practical examples on how to use the
questdlg command.

Close GUI Confirmation
I already covered a very good use of questdlg in a previous tutorial: Close confirmation for GUI. Using
the questdlg command, you can confirm if the user really wants to exit the GUI.

Save Data Confirmation
Along the same lines, you can program a GUI to ask for confirmation when the user is performing a
particular action. For instance, maybe the user did not save their data and tries to perform another
operation that would wipe out the current data.
ButtonName = questdlg('Do you want to save current data first?', ...
'Save Data', ...
'Yes', 'No', 'Yes');

%perform the following operation depending on the option chosen
switch ButtonName,
case 'Yes',
%add code here for saving data
case 'No',
%add code here when data is not saved
end % switch

Warn User of Excessive Processing Time
Perhaps the user is trying to process a data file that is very large and will take a long time. We can
warn the user with the following use of questdlg, allowing them to either continuing with the data
processing, or to abort it.
ButtonName = questdlg('Processing this file may take up to 30 minutes.', ...
'Process Data', ...
'Continue', 'Abort', 'Continue');

%perform the following operation depending on the option chosen
switch ButtonName,
case 'Continue',
%continue the current operation
case 'Abort',
%abort the current operation
end % switch

Versatile and Flexible
The questdlg command is very flexible and versatile and can be used in a variety of situations. There
are many situations wherein this command is useful which I did not discuss in this tutorial. After
reading this tutorial, I hope you are able to apply this knowledge and use it to create better interfaces!

Você também pode gostar