Create and Run a Simple figure-Based App

Note

This topic applies to apps you create programmatically using the figure function. For alternative ways to build apps, see Ways to Build Apps.

This example shows how to create a simple app programmatically, such as the one shown here.

Subsequent sections guide you through the process of creating this app.

If you prefer to view and run the code that created this app without creating it, set your current folder to one to which you have write access. Copy the example code and open it in the Editor by issuing the following MATLAB® commands:

copyfile(fullfile(docroot, 'techdoc','creating_guis',...
  'examples','simple_gui2*.*')), fileattrib('simple_gui2*.*', '+w');
edit simple_gui2.m
To run the code, go to the Run section in the Editor tab. Then click Run .

Create a Code File

Create a function file (as opposed to a script file, which contains a sequence of MATLAB commands but does not define functions).

  1. At the MATLAB prompt, type edit.

  2. Type the following statement in the first line of the Editor.

    function simple_gui2
  3. Following the function statement, type these comments, ending with a blank line. (The comments display at the command line in response to the help command.)

    % SIMPLE_GUI2 Select a data set from the pop-up menu, then
    % click one of the plot-type push buttons. Clicking the button
    % plots the selected data in the axes.
    (Leave a blank line here)
  4. At the end of the file, after the blank line, add an end statement. This end statement is required because the example uses nested functions. To learn more, see Nested Functions.

  5. Save the file in your current folder or at a location that is on your MATLAB path.

Create the Figure Window

To create a container for your app’s user interface (UI), add the following code before the end statement in your file:

%  Create and then hide the UI as it is being constructed.
f = figure('Visible','off','Position',[360,500,450,285]);

The call to the figure function creates a traditional figure and sets the following properties:

  • The Visible property is set to 'off' to make the window invisible as components are added or initialized. The window becomes visible when the UI has all its components and is initialized.

  • The Position property is set to a four-element vector that specifies the location of the UI on the screen and its size: [distance from left, distance from bottom, width, height]. Default units are pixels.

Add Components to the UI

Create the push buttons, static text, pop-up menu, and axes components to the UI.

  1. Following the call to figure, add these statements to your code file to create three push button components.

    % Construct the components.
    hsurf    = uicontrol('Style','pushbutton',...
                 'String','Surf','Position',[315,220,70,25]);
    hmesh    = uicontrol('Style','pushbutton',...
                 'String','Mesh','Position',[315,180,70,25]);
    hcontour = uicontrol('Style','pushbutton',...
                 'String','Contour','Position',[315,135,70,25]);

    Each statement uses a series of uicontrol property/value pairs to define a push button:

    • The Style property specifies that the uicontrol is a push button.

    • The String property specifies the label on each push button: Surf, Mesh, and Contour.

    • The Position property specifies the location and size of each push button: [distance from left, distance from bottom, width, height]. Default units for push buttons are pixels.

    Each uicontrol call returns the handle of the push button created.

  2. Add the pop-up menu and a text label by adding these statements to the code file following the push button definitions. The first statement creates the label. The second statement creates the pop-up menu.

    htext  = uicontrol('Style','text','String','Select Data',...
               'Position',[325,90,60,15]);
    hpopup = uicontrol('Style','popupmenu',...
               'String',{'Peaks','Membrane','Sinc'},...
               'Position',[300,50,100,25]);
    

    The pop-up menu component String property uses a cell array to specify the three items in the pop-up menu: Peaks, Membrane, and Sinc.

    The text component, the String property specifies instructions for the user.

    For both components, the Position property specifies the size and location of each component: [distance from left, distance from bottom, width, height]. Default units for these components are pixels.

  3. Add the axes by adding this statement to the code file.

    ha = axes('Units','pixels','Position',[50,60,200,185]);

    The Units property specifies pixels so that the axes has the same units as the other components.

  4. Following all the component definitions, add this line to the code file to align all components, except the axes, along their centers.

    align([hsurf,hmesh,hcontour,htext,hpopup],'Center','None');
  5. Add this command following the align command.

    f.Visible = 'on';

    Your code file should look like this:

    function simple_gui2
    % SIMPLE_GUI2 Select a data set from the pop-up menu, then
    % click one of the plot-type push buttons. Clicking the button
    % plots the selected data in the axes.
    
       %  Create and then hide the UI as it is being constructed.
       f = figure('Visible','off','Position',[360,500,450,285]);
       
       %  Construct the components.
       hsurf = uicontrol('Style','pushbutton','String','Surf',...
               'Position',[315,220,70,25]);
       hmesh = uicontrol('Style','pushbutton','String','Mesh',...
               'Position',[315,180,70,25]);
       hcontour = uicontrol('Style','pushbutton',...
               'String','Contour',...
               'Position',[315,135,70,25]); 
       htext = uicontrol('Style','text','String','Select Data',...
               'Position',[325,90,60,15]);
       hpopup = uicontrol('Style','popupmenu',...
               'String',{'Peaks','Membrane','Sinc'},...
               'Position',[300,50,100,25]);
       ha = axes('Units','Pixels','Position',[50,60,200,185]); 
       align([hsurf,hmesh,hcontour,htext,hpopup],'Center','None');
       
       % Make the UI visible.
       f.Visible = 'on';
    
    end
  6. Run your code by typing simple_gui2 at the command line. You can select a data set in the pop-up menu and click the push buttons, but nothing happens. This is because there is no callback code in the file to service the pop-up menu or the buttons.

Code the App Behavior

Program the Pop-Up Menu

The pop-up menu enables users to select the data to plot. When a user selects one of the three data sets in the pop-up menu, MATLAB software sets the pop-up menu Value property to the index of the selected menu item. The pop-up menu callback reads the pop-up menu Value property to determine which item is currently displayed and sets current_data accordingly.

Add the following callback to your file following the initialization code and before the final end statement.

%  Pop-up menu callback. Read the pop-up menu Value property to
%  determine which item is currently displayed and make it the
%  current data. This callback automatically has access to 
%  current_data because this function is nested at a lower level.
   function popup_menu_Callback(source,eventdata) 
      % Determine the selected data set.
      str = source.String;
      val = source.Value;
      % Set current data to the selected data set.
      switch str{val};
      case 'Peaks' % User selects Peaks.
         current_data = peaks_data;
      case 'Membrane' % User selects Membrane.
         current_data = membrane_data;
      case 'Sinc' % User selects Sinc.
         current_data = sinc_data;
      end
   end

Program the Push Buttons

Each of the three push buttons creates a different type of plot using the data specified by the current selection in the pop-up menu. The push button callbacks plot the data in current_data. They automatically have access to current_data because they are nested at a lower level.

Add the following callbacks to your file following the pop-up menu callback and before the final end statement.

% Push button callbacks. Each callback plots current_data in the
% specified plot type.

function surfbutton_Callback(source,eventdata) 
% Display surf plot of the currently selected data.
     surf(current_data);
end

function meshbutton_Callback(source,eventdata) 
% Display mesh plot of the currently selected data.
     mesh(current_data);
end

function contourbutton_Callback(source,eventdata) 
% Display contour plot of the currently selected data.
     contour(current_data);
end

Program the Callbacks

When the user selects a data set from the pop-up menu or clicks one of the push buttons, MATLAB software executes the callback associated with that particular event. Use each component's Callback property to specify the name of the callback with which each event is associated.

  1. To the uicontrol statement that defines the Surf push button, add the property/value pair

    'Callback',{@surfbutton_Callback}

    so that the statement looks like this:

    hsurf = uicontrol('Style','pushbutton','String','Surf',...
            'Position',[315,220,70,25],...
            'Callback',{@surfbutton_Callback});

    Callback is the name of the property. surfbutton_Callback is the name of the callback that services the Surf push button.

  2. To the uicontrol statement that defines the Mesh push button, add the property/value pair

    'Callback',@meshbutton_Callback
  3. To the uicontrol statement that defines the Contour push button, add the property/value pair

    'Callback',@contourbutton_Callback
  4. To the uicontrol statement that defines the pop-up menu, add the property/value pair

    'Callback',@popup_menu_Callback

For more information, see Write Callbacks for Apps Created Programmatically.

Initialize the UI

Initialize the UI, so it is ready when the window becomes visible. Make the UI behave properly when it is resized by changing the component and figure units to normalized. This causes the components to resize when the UI is resized. Normalized units map the lower-left corner of the figure window to (0,0) and the upper-right corner to (1.0, 1.0).

Replace this code in editor:

% Make the UI visible.
f.Visible = 'on';

with this code:

% Initialize the UI.
% Change units to normalized so components resize automatically.
f.Units = 'normalized';
ha.Units = 'normalized';
hsurf.Units = 'normalized';
hmesh.Units = 'normalized';
hcontour.Units = 'normalized';
htext.Units = 'normalized';
hpopup.Units = 'normalized';

% Generate the data to plot.
peaks_data = peaks(35);
membrane_data = membrane;
[x,y] = meshgrid(-8:.5:8);
r = sqrt(x.^2+y.^2) + eps;
sinc_data = sin(r)./r;

% Create a plot in the axes.
current_data = peaks_data;
surf(current_data);

% Assign a name to appear in the window title.
f.Name = 'Simple GUI';

% Move the window to the center of the screen.
movegui(f,'center')

% Make the UI visible.
f.Visible = 'on';

Verify Code and Run the App

Make sure your code appears as it should, and then run it.

  1. Verify that your code file looks like this:

    function simple_gui2
    % SIMPLE_GUI2 Select a data set from the pop-up menu, then
    % click one of the plot-type push buttons. Clicking the button
    % plots the selected data in the axes.
    
    %  Create and then hide the UI as it is being constructed.
    f = figure('Visible','off','Position',[360,500,450,285]);
    
    % Construct the components.
    hsurf    = uicontrol('Style','pushbutton',...
                 'String','Surf','Position',[315,220,70,25],...
                 'Callback',@surfbutton_Callback);
    hmesh    = uicontrol('Style','pushbutton',...
                 'String','Mesh','Position',[315,180,70,25],...
                 'Callback',@meshbutton_Callback);
    hcontour = uicontrol('Style','pushbutton',...
                 'String','Contour','Position',[315,135,70,25],...
                 'Callback',@contourbutton_Callback);
    htext  = uicontrol('Style','text','String','Select Data',...
               'Position',[325,90,60,15]);
    hpopup = uicontrol('Style','popupmenu',...
               'String',{'Peaks','Membrane','Sinc'},...
               'Position',[300,50,100,25],...
               'Callback',@popup_menu_Callback);
    ha = axes('Units','pixels','Position',[50,60,200,185]);
    align([hsurf,hmesh,hcontour,htext,hpopup],'Center','None');
    
    % Initialize the UI.
    % Change units to normalized so components resize automatically.
    f.Units = 'normalized';
    ha.Units = 'normalized';
    hsurf.Units = 'normalized';
    hmesh.Units = 'normalized';
    hcontour.Units = 'normalized';
    htext.Units = 'normalized';
    hpopup.Units = 'normalized';
    
    % Generate the data to plot.
    peaks_data = peaks(35);
    membrane_data = membrane;
    [x,y] = meshgrid(-8:.5:8);
    r = sqrt(x.^2+y.^2) + eps;
    sinc_data = sin(r)./r;
    
    % Create a plot in the axes.
    current_data = peaks_data;
    surf(current_data);
    
    % Assign the a name to appear in the window title.
    f.Name = 'Simple GUI';
    
    % Move the window to the center of the screen.
    movegui(f,'center')
    
    % Make the window visible.
    f.Visible = 'on';
    
    %  Pop-up menu callback. Read the pop-up menu Value property to
    %  determine which item is currently displayed and make it the
    %  current data. This callback automatically has access to 
    %  current_data because this function is nested at a lower level.
       function popup_menu_Callback(source,eventdata) 
          % Determine the selected data set.
          str = get(source, 'String');
          val = get(source,'Value');
          % Set current data to the selected data set.
          switch str{val};
          case 'Peaks' % User selects Peaks.
             current_data = peaks_data;
          case 'Membrane' % User selects Membrane.
             current_data = membrane_data;
          case 'Sinc' % User selects Sinc.
             current_data = sinc_data;
          end
       end
    
      % Push button callbacks. Each callback plots current_data in the
      % specified plot type.
    
      function surfbutton_Callback(source,eventdata) 
      % Display surf plot of the currently selected data.
           surf(current_data);
      end
    
      function meshbutton_Callback(source,eventdata) 
      % Display mesh plot of the currently selected data.
           mesh(current_data);
      end
    
      function contourbutton_Callback(source,eventdata) 
      % Display contour plot of the currently selected data.
           contour(current_data);
      end
    end
  2. Run your app by typing simple_gui2 at the command line. The initialization code causes it to display the default peaks data with the surf function, making the UI look like this.

  3. In the pop-up menu, select Membrane, and then click the Mesh button. The UI displays a mesh plot of the MathWorks® L-shaped Membrane logo.

  4. Try other combinations before closing the UI.

  5. Type help simple_gui2 at the command line. MATLAB software displays the help text.

    help simple_gui2
      SIMPLE_GUI2 Select a data set from the pop-up menu, then
      click one of the plot-type push buttons. Clicking the button
      plots the selected data in the axes.

Related Topics