www.gusucode.com > simulinkcoder 案例源码程序 matlab代码 > simulinkcoder/UseCondiInputBranchExecutionExample.m

    %% Use Conditional Input Branch Execution
% This example shows how to optimize the generated code for a model that
% contains Switch and Multiport Switch blocks. When you select the model
% configuration parameter *Conditional input branch execution*, Simulink
% executes only blocks that compute the control input and data input
% that the control input selects. This optimization improves execution
% speed.


% Copyright 2015 The MathWorks, Inc.
%% Example Model
% In this example, switch paths are conditionally executed. If |Switch1|
% control input is true, |Switch1| executes blocks grouped in the
% |Switch1:Path1| branch. If |Switch1| control input is false, |Switch1|
% executes blocks grouped in the |Switch1:Path2| branch. If |Switch1| executes
% blocks in the |Switch1:Path2| branch and |Switch2| control input is true,
% |Switch2| executes blocks in the |Switch2:Path1| branch. If |Switch2|
% control input is false, |Switch2| executes blocks in the |Switch2:Path2|
% branch. The pseudo code shows this logic.
model='rtwdemo_condinput';
open_system(model);

%% Generate Code
% The *Conditional input branch execution* parameter is on by default. Enter
% the following command-line API to turn off the parameter.
set_param(model, 'ConditionallyExecuteInputs', 'off');
%%
% Create a temporary folder for the build and inspection process.
currentDir=pwd;
[~,cgDir]=rtwdemodir();
%%
% Build the model.
rtwbuild(model)
%%
% View the generated code without the optimization. These lines of code are
% in the |rtwdemo_condinput.c| file.
cfile = fullfile(cgDir,'rtwdemo_condinput_grt_rtw','rtwdemo_condinput.c');
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize', 1, 0);
%%
% The generated code contains an |if-else| statement for the |Switch1| block
% and an |if| statement for the |Switch2| block. Therefore, the generated code
% for |Switch1:Path2| executes even if the |if| statement for
% |Switch1:Path1| evaluates to true.

%% Enable Optimization
% # Open the Configuration Parameters dialog box.
% # On the *All Parameters* tab, select *Conditional input branch execution*.
% Alternatively, you can use the command-line API to enable the optimization.
set_param(model, 'ConditionallyExecuteInputs','on');
%% Generate Code with Optimization
rtwbuild(model)
cfile = fullfile(cgDir,'rtwdemo_condinput_grt_rtw','rtwdemo_condinput.c');
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize', 1, 0);
%%
% The generated code contains one |if| statement. The generated code for
% |Switch1:Path2| only executes if the |if| statement evaluates to false.

%% Close Model and Code Generation Report
bdclose(model)
rtwdemoclean;
cd(currentDir)