Skip to Main Content Skip to Search
Product Documentation

A GUI to Set Simulink Model Parameters (GUIDE)

About the Simulink Model Parameters Example

This example illustrates how to create a GUI that sets the parameters of a Simulink® model. In addition, the GUI can run the simulation and plot the results in a figure window. The following figure shows the GUI after running three simulations with different values for controller gains.

F14 controller gain editor

The example illustrates a number of GUI building techniques:

View and Run the Simulink Parameters GUI

If you are reading this document in the MATLAB Help browser, you can access the example FIG-file and code file by clicking the following links. If you are reading this on the Web or in PDF form, go to the corresponding section in the MATLAB Help Browser to use the links.

If you intend to modify the layout or code of this GUI example, first save a copy of its code file and FIG-file to your current folder (you need write access to your current folder to do this). Follow these steps to copy the example files to your current folder and then to open them:

  1. Click here to copy the files to your current folder.

  2. Type guide f14ex or click here to open the FIG-file in GUIDE.

  3. Type edit f14ex or click here to open the code file in the Editor.

You can view the properties of any component by double-clicking it in the Layout Editor to open the Property Inspector for it. You can modify either the figure, the code, or both, and then save the GUI in your current folder using File > Save as from GUIDE. This saves both files, allowing you to rename them, if you choose.

To just inspect the GUI in GUIDE and run it, follow these steps instead:

  1. Click here to add the example files to the MATLAB path (only for the current session).

  2. Click here to run the f14ex GUI.

  3. Click here to display the GUI in the GUIDE Layout Editor (read only).

  4. Click here to display the GUI code file in the MATLAB Editor (read only).

How to Use the Simulink Parameters GUI

The GUI has a Help button. Clicking it opens an HTML file, f14ex_help.html, in the Help Browser. This file, which resides in the examples folder along with the GUI files, contains the following five sections of help text:

F14 Controller Gain Editor

You can use the F14 Controller Gain Editor to analyze how changing the gains used in the Proportional-Integral Controller affect the aircraft's angle of attack and the amount of G force the pilot feels.

Note that the Simulink diagram f14.mdl must be open to run this GUI. If you close the F14 Simulink model, the GUI reopens it whenever it requires the model to execute.

Change the Controller Gains

You can change gains in two blocks:

  1. The Proportional gain (Kf) in the Gain block

  2. The Integral gain (Ki) in the Transfer Function block

You can change either of the gains in one of the two ways:

  1. Move the slider associated with that gain.

  2. Type a new value into the Current value edit field associated with that gain.

The block's values are updated as soon as you enter the new value in the GUI.

Run the Simulation

Once you have set the gain values, you can run the simulation by clicking the Simulate and store results button. The simulation time and output vectors are stored in the Results list.

Plot the Results

You can generate a plot of one or more simulation results by selecting the row of results (Run1, Run2, etc.) in the Results list that you want to plot and clicking the Plot button. If you select multiple rows, the graph contains a plot of each result.

The graph is displayed in a figure, which is cleared each time you click the Plot button. The figure's handle is hidden so that only the GUI can display graphs in this window.

Remove Results

To remove a result from the Results list, select the row or rows you want to remove and click the Remove button.

Run the GUI

The GUI is nonblocking and nonmodal because it is designed to be used as an analysis tool.

GUI Options Settings

This GUI uses the following GUI option settings:

Open the Simulink Block Diagrams

This example is designed to work with the f14 Simulink model. Because the GUI sets parameters and runs the simulation, the f14 model must be open when the GUI is displayed. When the GUI runs, the model_open subfunction executes. The purpose of the subfunction is to:

Here is the code for the model_open subfunction:

function model_open(handles)
if  isempty(find_system('Name','f14')),
	open_system('f14'); open_system('f14/Controller')
	set_param('f14/Controller/Gain','Position',[275 14 340 56])
	figure(handles.F14ControllerEditor)
	set_param('f14/Controller Gain','Gain',...
		get(handles.KfCurrentValue,'String'))
	set_param(...
      'f14/Controller/Proportional plus integral compensator',...
      'Numerator',...
      get(handles.KiCurrentValue,'String'))
end

Program the Slider and Edit Text Components

In the GUI, each slider is coupled to an edit text component so that:

Slider Callback

The GUI uses two sliders to specify block gains because these components enable the selection of continuous values within a specified range. When a user changes the slider value, the callback executes the following steps:

Here is the callback for the Proportional (Kf) slider:

function KfValueSlider_Callback(hObject, eventdata, handles)
% Ensure model is open.
model_open(handles)
% Get the new value for the Kf Gain from the slider.
NewVal = get(hObject, 'Value');
% Set the value of the KfCurrentValue to the new value 
% set by slider.
set(handles.KfCurrentValue,'String',NewVal)
% Set the Gain parameter of the Kf Gain Block to the new value.
set_param('f14/Controller/Gain','Gain',num2str(NewVal))

While a slider returns a number and the edit text requires a string, uicontrols automatically convert the values to the correct type.

The callback for the Integral (Ki) slider follows an approach similar to the Proportional (Kf) slider's callback.

Current Value Edit Text Callback

The edit text box enables users to enter a value for the respective parameter. When the user clicks another component in the GUI after entering data into the text box, the edit text callback executes the following steps:

Here is the callback for the Kf Current value text box:

function KfCurrentValue_Callback(hObject, eventdata, handles)
% Ensure model is open.
model_open(handles)
% Get the new value for the Kf Gain.
NewStrVal = get(hObject, 'String');
NewVal = str2double(NewStrVal);
% Check that the entered value falls within the allowable range.
if  isempty(NewVal) || (NewVal< -5) || (NewVal>0),
   % Revert to last value, as indicated by KfValueSlider.
   OldVal = get(handles.KfValueSlider,'Value');
   set(hObject, 'String',OldVal)
else % Use new Kf value
   % Set the value of the KfValueSlider to the new value.
   set(handles.KfValueSlider,'Value',NewVal)
   % Set the Gain parameter of the Kf Gain Block 
   % to the new value.
   set_param('f14/Controller/Gain','Gain',NewStrVal)
end

The callback for the Ki Current value follows a similar approach.

Run the Simulation from the GUI

The GUI Simulate and store results button callback runs the model simulation and stores the results in the handles structure. Storing data in the handles structure simplifies the process of passing data to other subfunction since this structure can be passed as an argument.

When a user clicks the Simulate and store results button, the callback executes the following steps:

Here is the Simulate and store results button callback:

function SimulateButton_Callback(hObject, eventdata, handles)
[timeVector,stateVector,outputVector] = sim('f14');
% Retrieve old results data structure
if isfield(handles,'ResultsData') & 
~isempty(handles.ResultsData)
	ResultsData = handles.ResultsData;
	% Determine the maximum run number currently used.
	maxNum = ResultsData(length(ResultsData)).RunNumber;
	ResultNum = maxNum+1;
else % Set up the results data structure
	ResultsData = struct('RunName',[],'RunNumber',[],...
	              'KiValue',[],'KfValue',[],'timeVector',[],...
	              'outputVector',[]);
	ResultNum = 1;
end
if isequal(ResultNum,1),
	% Enable the Plot and Remove buttons
	set([handles.RemoveButton,handles.PlotButton],'Enable','on')
end
% Get Ki and Kf values to store with the data and put in the 
results list.
Ki = get(handles.KiValueSlider,'Value');
Kf = get(handles.KfValueSlider,'Value');
ResultsData(ResultNum).RunName = ['Run',num2str(ResultNum)];
ResultsData(ResultNum).RunNumber = ResultNum;
ResultsData(ResultNum).KiValue = Ki;
ResultsData(ResultNum).KfValue = Kf;
ResultsData(ResultNum).timeVector = timeVector;
ResultsData(ResultNum).outputVector = outputVector;
% Build the new results list string for the listbox
ResultsStr = get(handles.ResultsList,'String');
if isequal(ResultNum,1)
	ResultsStr = {['Run1',num2str(Kf),' ',num2str(Ki)]};
else
	ResultsStr = [ResultsStr;...
	{['Run',num2str(ResultNum),' ',num2str(Kf),' ', ...
	num2str(Ki)]}];
end
set(handles.ResultsList,'String',ResultsStr);
% Store the new ResultsData
handles.ResultsData = ResultsData;
guidata(hObject, handles)

Remove Results from List Box

The GUI Remove button callback deletes any selected item from the Results list list box. It also deletes the corresponding run data from the handles structure. When a user clicks the Remove button, the callback executes the following steps:

Here is the Remove button callback:

function RemoveButton_Callback(hObject, eventdata, handles)
currentVal = get(handles.ResultsList,'Value');
resultsStr = get(handles.ResultsList,'String');
numResults = size(resultsStr,1);
% Remove the data and list entry for the selected value
resultsStr(currentVal) =[];
handles.ResultsData(currentVal)=[];
% If there are no other entries, disable the Remove and Plot 
button
% and change the list string to <empty>
if isequal(numResults,length(currentVal)),
	resultsStr = {'<empty>'};
	currentVal = 1;
	
set([handles.RemoveButton,handles.PlotButton],'Enable','off')	
end
% Ensure that list box Value is valid, then reset Value and String
currentVal = min(currentVal,size(resultsStr,1));
set(handles.ResultsList,'Value',currentVal,'String',resultsStr)
% Store the new ResultsData
guidata(hObject, handles)

Plot Results Data

The GUI Plot button callback creates a plot of the run data and adds a legend. The data to plot is passed to the callback in the handles structure, which also contains the gain settings used when the simulation ran. When a user clicks the Plot button, the callback executes the following steps:

Plot Into the Hidden Figure

The figure that contains the plot is created as invisible and then made visible after adding the plot and legend. To prevent this figure from becoming the target for plotting commands issued at the command line or by other GUIs, its HandleVisibility and IntegerHandle properties are set to off. This means the figure is also hidden from the plot and legend commands.

Use the following steps to plot into a hidden figure:

Plot Button Callback Listing

Here is the Plot button callback.

function PlotButton_Callback(hObject, eventdata, handles)
currentVal = get(handles.ResultsList,'Value');
% Get data to plot and generate command string with color 
% specified
legendStr = cell(length(currentVal),1);
plotColor = {'b','g','r','c','m','y','k'};
for ctVal = 1:length(currentVal);
	PlotData{(ctVal*3)-2} = 
handles.ResultsData(currentVal(ctVal)).timeVector;
	PlotData{(ctVal*3)-1} = 
handles.ResultsData(currentVal(ctVal)).outputVector;	
	numColor = ctVal - 7*( floor((ctVal-1)/7) );
	PlotData{ctVal*3} = plotColor{numColor};
	legendStr{ctVal} = ...
      [handles.ResultsData(currentVal(ctVal)).RunName,'; Kf=',...
      num2str(handles.ResultsData(currentVal(ctVal)).KfValue),...
      ';  Ki=', ...
      num2str(handles.ResultsData(currentVal(ctVal)).KiValue)];
end
% If necessary, create the plot figure and store in handles
% structure
if ~isfield(handles,'PlotFigure') ||...
   ~ishandle(handles.PlotFigure),
	handles.PlotFigure = ...
        figure('Name','F14 Simulation Output',...
        'Visible','off','NumberTitle','off',...
        'HandleVisibility','off','IntegerHandle','off');
	handles.PlotAxes = axes('Parent',handles.PlotFigure);
	guidata(hObject, handles)
end
% Plot data
pHandles = plot(PlotData{:},'Parent',handles.PlotAxes);
% Add a legend, and bring figure to the front
legend(pHandles(1:2:end),legendStr{:})
% Make the figure visible and bring it forward
figure(handles.PlotFigure)

The GUI Help Button

The GUI Help button callback displays an HTML file in the MATLAB Help browser. It uses two commands:

This is the Help button callback.

function HelpButton_Callback(hObject, eventdata, handles)
HelpPath = which('f14ex_help.html');
web(HelpPath); 

You can also display the help document in a Web browser or load an external URL. For a description of these options, see the documentation for the web function.

Close the GUI

The GUI Close button callback closes the plot figure, if one exists and then closes the GUI. The handle of the plot figure and the GUI figure are available from the handles structure. The callback executes two steps:

This is the Close button callback:

function CloseButton_Callback(hObject, eventdata, handles)
% Close the GUI and any plot window that is open
if isfield(handles,'PlotFigure') && ...
      ishandle(handles.PlotFigure),
   close(handles.PlotFigure);
end
close(handles.F14ControllerEditor); 

The List Box Callback and Create Function

This GUI does not use the list box callback because the actions performed on list box items are carried out by push buttons (Simulate and store results, Remove, and Plot). GUIDE automatically inserts a callback stub when you add the list box and automatically sets the Callback property to execute this subfunction whenever the callback is triggered (which happens when users select an item in the list box).

In this example, there is no need for the list box callback to execute. You can delete it from the GUI code file and at the same time also delete the Callback property string in the Property Inspector so that the software does not attempt to execute the callback.

Property Inspector showing deleted call back property string

For more information on how to trigger the list box callback, see the description of list box.

Set the Background to White

The list box create function enables you to determine the background color of the list box. The following code shows the create function for the list box that is tagged ResultsList:

function ResultsList_CreateFcn(hObject, eventdata, handles)
% Hint: listbox controls usually have a white background, change
%       'usewhitebg' to 0 to use default. See ISPC and COMPUTER.
usewhitebg = 1;
if usewhitebg
    set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',...
    get(0,'defaultUicontrolBackgroundColor'));
end
  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS