UCL Department of Phonetics and Linguistics

Introduction to Computer Programming with MATLAB

Lecture 7: Building a Graphical User Interface



By the end of the session you should:

q       know how to build a simple single-figure dialog to control your application

q       know how to add menus, figures, text, buttons and edit boxes to your dialog

q       know how to associate MATLAB code to events generated by the dialog controls

q       know how to retrieve and modify the properties of the dialog controls

q       know how to set up a single control file for your dialog



1.      Elements of a Graphical User Interface


By a graphical user interface, we mean that we can give a MATLAB program the look and feel of a typical Windows application.  The MATLAB GUI design system allows you to create applications consisting of one or more ‘dialogs’ containing typical ‘controls’ such as buttons, edit boxes, lists and pictures.


One of the important aspects of a Windows application that is unlike the kind of programs we have considered up to now is that they interact asynchronously with the user.  The user can select any function of the program at any time.  This means that you need to store the ‘state’ of your program in a set of variables and be prepared to execute any function based on the current state at any time.


The MATLAB GUI design system helps you in this by associating functions with each element of the dialog.  Thus when you press a button, click on a menu, or enter a number in an edit box, you can arrange for a function in your program to be called.  Your task is to program the actions related to that function, e.g. opening a file, playing a sound, or displaying the results of a calculation.


The most common controls are:

q       Menu options.  Selection calls up an operation by name.

q       Push buttons. Clicking calls up some operation.

q       Edit boxes.  User can enter some text or numerical value.

q       List boxes. User can choose among list of items.

q       Figures. Program can display graphical results.

q       Text.  Program can display textual result.


You can use the controls themselves to store data or you can create a set of global variables.


2.      How to build a simple dialogue


To start the design  program type 'guide' at the MATLAB prompt.  You are presented with a blank form upon which you can position controls.  Choose a control from the palette and click and size the control on the page to position it.  Each control is automatically given a name based on its type.


When the layout is complete, you can save the design to a ‘.fig’ file.  This will automatically create a matching ‘.m’ program file which you can use to launch the application and store the code that is operated by the controls.  It is not necessary to store all your code in the matching ‘.m’ file; indeed it is a good idea to break up any large sections of code into its own function blocks stored in separate files.  You will see that the layout designer builds a ‘callback’ function prototype in the program file for each control that provides input to the application.  This function will be called automatically when that control is activated.


You can edit the properties of the controls on the layout editor by right-clicking on them and choosing ‘Property Inspector’.  In particular the ‘String’ property is used to store the default text for buttons, list boxes and edit boxes.  The ‘Tag’ property is the name of the control; and until you are familiar with MATLAB, it is advisable not to change the default name.  You can also use the Property Inspector to change the name of the dialog itself.


You can add menu options to your dialog with the ‘Menu Editor’.  If you leave the callback function entry as “%automatic”, then the menu editor adds callback functions to your program for each menu item.  Otherwise create your own callback function using existing ones as a model, and associate a call to the function with the menu item manually.


It is important to realise that the ‘.m’ file associated with your application is executed afresh each time there is some event in the dialog.  That is you must store the ‘current state’ of the program in global variables in the workspace, and not in variables local to a function.  You can ensure this by using a ‘global’statement and initialising them in the part of the file where the figure is initialised.


You can access any property of any control using the ‘Tag’ property of the control and the MATLAB ‘get()’ and ‘set()’ functions.

value = get(handles.ControlTagName,'PropertyName');


For example:

text = get(handles.edit1,'String');


Note that most properties have to be get() and set() as strings.  Use the num2str() and str2num() functions to help convert between strings and numeric values.


3.      Worked example



function varargout = beatsdemo(varargin)

% BEATSDEMO M-file for beatsdemo.fig

%      BEATSDEMO, by itself, creates a new BEATSDEMO or raises the existing

%      singleton*.


%      H = BEATSDEMO returns the handle to a new BEATSDEMO or the handle to

%      the existing singleton*.


%      BEATSDEMO('CALLBACK',hObject,eventData,handles,...) calls the local

%      function named CALLBACK in BEATSDEMO.M with the given input arguments.


%      BEATSDEMO('Property','Value',...) creates a new BEATSDEMO or raises the

%      existing singleton*.  Starting from the left, property value pairs are

%      applied to the GUI before beatsdemo_OpeningFunction gets called.  An

%      unrecognized property name or invalid value makes property application

%      stop.  All inputs are passed to beatsdemo_OpeningFcn via varargin.


%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one

%      instance to run (singleton)".




% Edit the above text to modify the response to help beatsdemo


% Last Modified by GUIDE v2.5 11-Dec-2005 15:46:27

% Begin initialization code - DO NOT EDIT

gui_Singleton = 1;

gui_State = struct('gui_Name',       mfilename, ...

                   'gui_Singleton',  gui_Singleton, ...

                   'gui_OpeningFcn', @beatsdemo_OpeningFcn, ...

                   'gui_OutputFcn',  @beatsdemo_OutputFcn, ...

                   'gui_LayoutFcn',  [] , ...

                   'gui_Callback',   []);

if nargin & isstr(varargin{1})

    gui_State.gui_Callback = str2func(varargin{1});



if nargout

    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});


    gui_mainfcn(gui_State, varargin{:});


% End initialization code - DO NOT EDIT


% --- Executes just before beatsdemo is made visible.

function beatsdemo_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 beatsdemo (see VARARGIN)


% Choose default command line output for beatsdemo

handles.output = hObject;


% Update handles structure

guidata(hObject, handles);



% initialise global variable cf

global cf;




% --- Outputs from this function are returned to the command line.

function varargout = beatsdemo_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;

% --- 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

%%%%%%%%%%%%%%%%%%%%%%%% Callback Functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%
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)

% just call the pushbutton if text changes ...

% --- 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)

% reference global variable

global cf;

% get beat frequency from text box


% make beats by combining two sinewaves




% set default axes to figure and plot



% --------------------------------------------------------------------
function menu1000_Callback(hObject, eventdata, handles)
% hObject    handle to f1000 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global cf;



set(handles.text1,'String','Beats Demonstration (1000Hz)');


% --------------------------------------------------------------------
function menu2000_Callback(hObject, eventdata, handles)
% hObject    handle to f2000 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global cf;



set(handles.text1,'String','Beats Demonstration (2000Hz)');




MATLAB Online Manual: Creating Graphical User Interfaces



For these exercises, use the editor window to enter your code, and save your answers to files under your account on the central server. When you save the files, give them the file extension of ".m".  Run your programs from the command window.

1.      Write a program (ex71.fig, ex71.m, sinewave.m) that shows a dialog containing four buttons.  The buttons have labels: ‘250Hz’, ‘500Hz’, ‘1000Hz’ and ‘2000Hz’.  When you click on them a 1 second tone of the specified frequency is replayed.

2.      Modify the last example (ex72.fig, ex72.m) to display the first 0.01 second of the tone as well.

3.      Modify the last example (ex73.fig, ex73.m) to allow the user to specify the frequency of one tone.

4.      Modify the last example (ex74.fig, ex74.m, waveform.m) to provide a menu option to select between a sine wave, a pulse train and a square wave.  Report the currently selected waveform type in a text field.

5.      (Homework)  The following MATLAB command

[filename, pathname] = uigetfile('*.wav', 'Pick a WAV file');

will display a Windows dialog box allowing you select a file.  The name of the file and the name of the containing folder are returned.  Build a GUI application which allows you to (i) open a WAV file and display it, (ii) play out the audio at the correct and at user specified sampling rates.