Results 1 to 1 of 1

Thread: MATLAB GUI Tutorial

  1. #1
    Mar 2007

    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

    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)
    padx = 50;%x pading for everything relative to main figure
    pady = 45;
    ipadx = 5;%x pading between items within the main figure
    ipady = 5;
    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, ...
    set(h.mainFig,'MenuBar','None')%Remove default figure menubar
    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
    h.axes = axes('Unit','pixel','Position',[padx pady myGUI_width-2*padx myGUI_height-160]);
    %add labels for sliders
    h.txt_a = uicontrol('style','text','Position',[padx (myGUI_height-pady-0*(widgetH+ipady)) 3*widgetH widgetH], ...
        'string',['a= ' num2str(h.a)]);
    h.txt_b = uicontrol('style','text','Position',[padx (myGUI_height-pady-1*(widgetH+ipady)) 3*widgetH widgetH], ...
        'string',['b= ' num2str(h.b)]);
    h.txt_c = uicontrol('style','text','Position',[padx (myGUI_height-pady-2*(widgetH+ipady)) 3*widgetH widgetH], ...
        'string',['c= ' num2str(h.c)]);
    %create sliders
    %slider StepSize = (max-min)/number_of_steps     ==>(use 40 steps)
    slider_width = myGUI_width-(2*padx+3*widgetH+ipadx);%all sliders to be this long
    h.slider_a = uicontrol('style','slider', ...
        'Position',[(padx+3*widgetH+ipadx) (myGUI_height-pady-0*(widgetH+ipady)) slider_width widgetH], ...
        'Min',-10,'Max',10,'Value',h.a,'SliderStep',[0.025 0.025]);
    h.slider_b = uicontrol('style','slider', ...
        'Position',[(padx+3*widgetH+ipadx) (myGUI_height-pady-1*(widgetH+ipady)) slider_width widgetH], ...
        'Min',-10,'Max',10,'Value',h.b,'SliderStep',[0.025 0.025]);
    h.slider_c = uicontrol('style','slider', ...
        'Position',[(padx+3*widgetH+ipadx) (myGUI_height-pady-2*(widgetH+ipady)) slider_width widgetH], ...
        'Min',-10,'Max',10,'Value',h.c,'SliderStep',[0.025 0.025]);
    editH = (myGUI_height-pady-3*(widgetH+ipady));%height to place edit boxes at
    %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
    h.txt_xmin = uicontrol('style','text','Position',[(padx+0*(widgetH+ipadx)) editH 2*widgetH widgetH], ...
    h.txt_xmax = uicontrol('style','text','Position',[(padx+5*(widgetH+ipadx)) editH 2*widgetH widgetH], ...
    h.txt_N = uicontrol('style','text','Position',[(padx+10*(widgetH+ipadx)) editH 2*widgetH widgetH], ...
    %create edit boxes for xmin xmax and number of points
    h.edit_xmin = uicontrol('style','edit','Position',[(padx+2*(widgetH+ipadx)) editH 2*widgetH widgetH], ...
    h.edit_xmax = uicontrol('style','edit','Position',[(padx+7*(widgetH+ipadx)) editH 2*widgetH widgetH], ...
    h.edit_n = uicontrol('style','edit','Position',[(padx+12*(widgetH+ipadx)) editH 2*widgetH widgetH], ...
    %=======================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
    function slider_b_Callback(hObject, eventdata, h)
    h = guidata(hObject);
    val = get(hObject,'Value');
    str = sprintf('b=%0.1f',val);
    h.b = val;
    function slider_c_Callback(hObject, eventdata, h)
    h = guidata(hObject);
    val = get(hObject,'Value');
    str = sprintf('c=%0.1f',val);
    h.c = val;
    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
    function edit_xmax_Callback(hObject, eventdata, h)
    h = guidata(hObject);
    xmax = str2double(get(hObject,'String'));
    h.xmax = xmax;
    function edit_n_Callback(hObject, eventdata, h)
    h = guidata(hObject);
    n = str2double(get(hObject,'String'));
    h.n = n;
    %=======================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:
    h.slider_a = uicontrol('style','slider', ...
        'Position',[(padx+3*widgetH+ipadx) (myGUI_height-pady-0*(widgetH+ipady)) slider_width widgetH], ...
        '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)
    5)write any additional functions to perform routine tasks.

    The key concepts that you need to look into when writing GUI's and dealing with figures in "handles". MATLAB uses a handles structure as a way to contain all the references to each control within the GUI. In the example above, this handles structure was called "h". I also added my own data which were not handles to the handles structure using the function "guidata". This allowed me to access common information between different controls without using global variables.

    This tutorial is a work in progress so please bare with me while I continue to update this post to explain the process above.

    Regards Elbarto
    Last edited by elbarto; Nov 2nd 2009 at 07:36 PM.
    Follow Math Help Forum on Facebook and Google+

Similar Math Help Forum Discussions

  1. LaTex Tutorial
    Posted in the LaTeX Help Forum
    Replies: 102
    Last Post: May 3rd 2009, 01:13 PM
  2. LaTex Tutorial
    Posted in the LaTeX Help Forum
    Replies: 99
    Last Post: Aug 25th 2008, 07:02 PM
  3. Derivative Tutorial
    Posted in the Calculus Forum
    Replies: 47
    Last Post: Apr 24th 2008, 05:51 PM

Search Tags

/mathhelpforum @mathhelpforum