www.gusucode.com > ecoder 案例源码程序 matlab代码 > ecoder/ConsolidateRedundantIfElseStatementsExample.m

    %% Optimize Generated Code by Consolidating Redundant If-Else Statements 
% This example shows how to optimize generated code by combining |if-else|
% statements that share the same condition. This optimization:
%
% * Improves control flow.
% * Reduces code size.
% * Reduces RAM consumption.
% * Increases execution speed.


%% Example
% The model <matlab:rtwdemo_controlflow_opt rtwdemo_controlflow_opt> contains three Switch blocks.
% The Constant block provides the control input to the Switch blocks. The
% variable named |Cond| determines the value of the Constant block.
% 
model = 'rtwdemo_controlflow_opt';
open_system(model);

%% Generate Code 
% Create a temporary folder for the build and inspection process.
% 
currentDir = pwd;
[~,cgDir] = rtwdemodir();

%%
% Build the model.
rtwbuild(model)

%%
% These lines of |rtwdemo_controlflow_opt.c| code show that in the generated
% code, two |if-else| statements and one |else-if| statement represent the
% three Switch blocks.
% 
% 
cfile = fullfile(cgDir,'rtwdemo_controlflow_opt_ert_rtw',...
    'rtwdemo_controlflow_opt.c');
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize', 1, 0);

%% Enable Optimization
% # Open the Configuration Parameters dialog box.  
% # On the *Code generation*-> *Code Style* pane, clear *Preserve
% condition expression in if statement*. This parameter is on by default.
%
% Alternatively, use the command-line API to turn off the parameter:
set_param(model, 'PreserveIfCondition', 'off');

%% Generate Code with Optimization
% In the optimized code, the code generator consolidates the two |if-else|
% statements and one |else-if| statement into one |if-else| statement. The code
% generator consolidates these statements because they all share the
% same condition. There is no intervening code that affects the outcomes of
% these statements.
%
%
%%
% Build the model.
rtwbuild(model)

%%
% Here is the |rtwdemo_controlflow_opt.c| optimized code.
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize', 1, 0);

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