%% Optimize Generated Code Using Specified Minimum and Maximum Values
% This example shows how the minimum and maximum values specified on signals
% and parameters in a model are used to optimize the generated code.

%   Copyright 2010-2012 The MathWorks, Inc.

%% Overview
% The specified minimum and maximum values usually represent environmental
% limits, such as temperature, or mechanical and electrical limits, such as
% output ranges of sensors.
%
% This optimization uses these values to streamline the generated code. For
% example, it reduces expressions to constants or removes dead branches of
% conditional statements.
%
% *NOTE:* Make sure the minimum and maximum values that you specify are
% valid limits.  Otherwise, this optimization might result in
% numerical mismatch with simulation.
%
% The benefits of optimizing the generated code are:
%
% * Reducing the ROM and RAM consumption.
% * Improving the execution speed.


%% Review Minimum and Maximum Information
% Consider the model <matlab:rtwdemo_minmax rtwdemo_minmax>.
% In this model, there are minimum and maximum values specified on Inports and
% on the gain parameter of the Gain block.
model = 'rtwdemo_minmax';
open_system(model);

%% Generate Code Without This Optimization
% 
% First, generate code for this model without considering the min and max values.
currentDir = pwd;
[~,cgDir] = rtwdemodir();
rtwconfiguredemo(model,'ERT')
rtwbuild(model)

%%
% A portion of |rtwdemo_minmax.c| is listed below.
cfile = fullfile(cgDir,'rtwdemo_minmax_ert_rtw','rtwdemo_minmax.c');
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize', 1, 0);

%% Enable This Optimization
% # Open the Configuration Parameters dialog box.  
% # On the *Optimization* pane, select 
%   *Optimize using the specified minimum and maximum values*.
%
% Alternatively, you can enable this optimization by setting the command-line
% parameter.
set_param(model, 'UseSpecifiedMinMax', 'on');

%% Generate Code With This Optimization
% In the model, with the specified minimum and maximum values for |U1| and |U2|,
% the sum of |U1| and |U2| has a minimum value of 50. Considering the
% range of |U3|
% and the specified minimum and maximum values for the Gain block parameter, the
% maximum value of the Gain block's output is 40.
%
% The output of the Relational Operator block remains false, and
% the output of the Switch block remains the product of the three inputs.
%

%%
% Configure and build the model using Embedded Coder.
rtwconfiguredemo(model,'ERT')
rtwbuild(model)

%%
% View the optimized code from |rtwdemo_minmax.c|.
cfile = fullfile(cgDir,'rtwdemo_minmax_ert_rtw','rtwdemo_minmax.c');
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize', 1, 0);

%%
% Close the model and cleanup.
bdclose(model)
rtwdemoclean;
cd(currentDir)
