# Math Help - MATLAB GUI Tutorial

1. ## MATLAB GUI Tutorial

This tutorial is aimed at showing users how to created Graphical User Interfaces (GUI's) for their MATLAB application by programming the entire GUI by hand. MATLAB has a tool for building GUI's called GUIDE, which allows you to visually create the GUI then add functionality to it later. I have chosen to use the hand coded method instead of useing GUIDE as it shows a lot more about how the GUI is actually working as MATLAB writes some pretty cryptic code for you when developing a GUI in GUIDE. This is not to say that GUIDE is a bad thing, I have just started working with GUI's so I thought I would make a post to help others learn from my recent experience. I learned a lot from this video MATLAB Basics: GUIs without GUIDE | File Exchange Pick of the Week. This tutorial should provide enough information on some of the queries I found to help new users add another dimension to their applications.

The entire code for the GUI used in this thread is given below. Create a new mfile and paste the code in then save as myGUI.m

Code:
function h = myGUI(sz)
% V1.1
% myGUI is a simple example of contructing GUI's from the MATLAB
% editor rather then using GIUDE. This example creates a window
% of size sz where sz = [width height]. The quadratic equation has
% been used as a simple model to demonstrate how each of the controls (I
% also refer to these as widgets on occasion).

%if user doesn't specify size, use the following as default
if nargin < 1;sz = [600 480];end
myGUI_width = sz(1);%GUI width (pixels)
myGUI_height = sz(2);%GUI height (pixels)

widgetH = 16;%height to make widgets (ie controls)

%add data that needs to be shared and accessed by different controls
%and function to the handles structure "h". This structure will passed
%to each control Callback when executed.
h.xmin = -10;%min x value to plot
h.xmax = 10;%max x value to plot
h.n = 20;%number of values to plot
h.a = 1;% coeficients for a*x^2+b*x+c
h.b = 0;% coeficients for a*x^2+b*x+c
h.c = 1;% coeficients for a*x^2+b*x+c

%=======================BEGIN CREATING LAYOUT=============================
%To set the position of a control, you need to specify the following:
%[distance_from_left_edge distance_from_bottom_edge width height]

%create the main figure (mainFig) in middle of screen.
%Store all control handles in structure "h"
scrsz = get(0,'ScreenSize');%get screen size
h.mainFig = figure('Position',[ ...
(scrsz(3)-myGUI_width)/2, ...
(scrsz(4)-myGUI_height)/2, ...
myGUI_width, ...
myGUI_height]);
set(h.mainFig,'ToolBar','None')%Remove default figure toolbar
set(h.mainFig,'Resize','off')%prevent window from being resized
set(h.mainFig,'Name','Quadratic Calulator')%prevent window from being resized
%I could have placed all of these inside the above statement where I
%set the position, but prefer this method as it is easier to read.

%add some axes to plot on
%I have used pixels as the units to describe the position so the
%padding between the axes and other controls does not change if a
%bigger window size is used for mainFig

'string',['a= ' num2str(h.a)]);
'string',['b= ' num2str(h.b)]);
'string',['c= ' num2str(h.c)]);

%create sliders
%slider StepSize = (max-min)/number_of_steps     ==>(use 40 steps)
h.slider_a = uicontrol('style','slider', ...
'Min',-10,'Max',10,'Value',h.a,'SliderStep',[0.025 0.025]);
h.slider_b = uicontrol('style','slider', ...
'Min',-10,'Max',10,'Value',h.b,'SliderStep',[0.025 0.025]);
h.slider_c = uicontrol('style','slider', ...
'Min',-10,'Max',10,'Value',h.c,'SliderStep',[0.025 0.025]);

%create lables for edit boxes for xmin xmax and number of points
boxColour = get(h.mainFig,'Color');%set the background of these boxes the same as mainFig
'string','xmin=','HorizontalAlignment','right','BackgroundColor',boxColour);
'string','xmax=','HorizontalAlignment','right','BackgroundColor',boxColour);
'string','n=','HorizontalAlignment','right','BackgroundColor',boxColour);

%create edit boxes for xmin xmax and number of points
'string',-10,'HorizontalAlignment','left','BackgroundColor',boxColour);
'string',10,'HorizontalAlignment','left','BackgroundColor',boxColour);
'string',20,'HorizontalAlignment','left','BackgroundColor',boxColour);
%=======================END CREATING LAYOUT=============================

%=======================BEGIN SETTING CALBACKS=============================
%set callbacks for sliders
set(h.slider_a,'callback',{@slider_a_Callback h});
set(h.slider_b,'callback',{@slider_b_Callback h});
set(h.slider_c,'callback',{@slider_c_Callback h});
%set callbacks for edit boxes
set(h.edit_xmin,'callback',{@edit_xmin_Callback h});
set(h.edit_xmax,'callback',{@edit_xmax_Callback h});
set(h.edit_n,'callback',{@edit_n_Callback h});
%=======================END SETTING CALBACKS=============================

guidata(h.mainFig,h)%update the entire handle structure to include everything defined above
updatePlot(h);%plot the default values initially

%=======================BEGIN DEFINING CALBACKS=============================
function slider_a_Callback(hObject, eventdata, h)
h = guidata(hObject);%get the entire handle structure for the GUI
val = get(hObject,'Value');%get the value from the slider
str = sprintf('a=%0.1f',val);%create a string
set(h.txt_a,'String',str);%put string in text box for a
h.a = val;%update handles
guidata(hObject,h);%update entire handle structure
updatePlot(h);%replot

function slider_b_Callback(hObject, eventdata, h)
h = guidata(hObject);
val = get(hObject,'Value');
str = sprintf('b=%0.1f',val);
set(h.txt_b,'String',str);
h.b = val;
guidata(hObject,h);
updatePlot(h);

function slider_c_Callback(hObject, eventdata, h)
h = guidata(hObject);
val = get(hObject,'Value');
str = sprintf('c=%0.1f',val);
set(h.txt_c,'String',str);
h.c = val;
guidata(hObject,h);
updatePlot(h);

function edit_xmin_Callback(hObject, eventdata, h)
h = guidata(hObject);%get the entire handle structure for the GUI
xmin = str2double(get(hObject,'String'));%get the value of the box
h.xmin = xmin;%update handles
guidata(hObject,h)%update entire handle structure
updatePlot(h);%replot

function edit_xmax_Callback(hObject, eventdata, h)
h = guidata(hObject);
xmax = str2double(get(hObject,'String'));
h.xmax = xmax;
guidata(hObject,h)
updatePlot(h);

function edit_n_Callback(hObject, eventdata, h)
h = guidata(hObject);
n = str2double(get(hObject,'String'));
h.n = n;
guidata(hObject,h)
updatePlot(h);
%=======================END DEFINING CALBACKS=============================

function updatePlot(h)
%This is the function that that makes use off all data that
%has been stored by the controls in the GUI
h = guidata(h.mainFig);%get the entire handle structure for the GUI
x = linspace(h.xmin,h.xmax,h.n);%create n values of x between xmin and xmax
y = h.a*x.^2+h.b*x+h.c;%calculate y values
axes(h.axes)%set axis to plot on
plot(x,y,'o-');%plot data
axis equal%axis are the same scale
xlabel x
ylabel y
legend('y = a*x^2+b*x+c')

While the code appears to be quite long, it is quite repetitive since we are making alot of controls that are very similar to each other. The majority of the hard to read code is for positioning the controls in the right spot on the form. ie:
Code:
h.slider_a = uicontrol('style','slider', ...
'Min',-10,'Max',10,'Value',h.a,'SliderStep',[0.025 0.025]);
This simply creates a slider with a range of [-10 10], with the default value of h.a as defined in previous code and it uses 40 steps ie 1/0.025. The rest of the code is to do with possitioning the control as indicated by the keyword "Position". To make positioning the controls easier, I have used variables like slider_width and widgetH so I can easily change the layout of the GUI later if I wish. This is a good practice to get into when dealing with multiple controls as it saves changing the properties of every control in the event you need to change something.

The step to create a GUI such as these are:
1) Create a main figure
2)create controls - (this is where most of the code is, GUIDE builds this code for you but not in the same form that we used here).
3)define Callbacks for controls (ie what function should execute when a button is clicked for example)
4)Write code for Callbacks (ie write the code inside the defined functions from previous step)