Results 1 to 1 of 1

Math Help - MATLAB GUI Tutorial

  1. #1
    Member
    Joined
    Mar 2007
    Posts
    206
    Awards
    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)
    
    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, ...
        myGUI_height]);  
    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], ...
        'string','xmin=','HorizontalAlignment','right','BackgroundColor',boxColour);
    h.txt_xmax = uicontrol('style','text','Position',[(padx+5*(widgetH+ipadx)) editH 2*widgetH widgetH], ...
        'string','xmax=','HorizontalAlignment','right','BackgroundColor',boxColour);
    h.txt_N = uicontrol('style','text','Position',[(padx+10*(widgetH+ipadx)) editH 2*widgetH widgetH], ...
        'string','n=','HorizontalAlignment','right','BackgroundColor',boxColour);
    
    %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], ...
        'string',-10,'HorizontalAlignment','left','BackgroundColor',boxColour);
    h.edit_xmax = uicontrol('style','edit','Position',[(padx+7*(widgetH+ipadx)) editH 2*widgetH widgetH], ...
        'string',10,'HorizontalAlignment','left','BackgroundColor',boxColour);
    h.edit_n = uicontrol('style','edit','Position',[(padx+12*(widgetH+ipadx)) editH 2*widgetH widgetH], ...
        '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', ...
        '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; November 2nd 2009 at 08: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, 02:13 PM
  2. LaTex Tutorial
    Posted in the LaTeX Help Forum
    Replies: 99
    Last Post: August 25th 2008, 08:02 PM
  3. Derivative Tutorial
    Posted in the Calculus Forum
    Replies: 47
    Last Post: April 24th 2008, 06:51 PM

Search Tags


/mathhelpforum @mathhelpforum