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

    %% Fold Expressions
% Expression folding optimizes code to minimize the computation of
% intermediate results at block outputs and the storage of such results in
% temporary buffers or variables. When expression folding is on, the code
% generator collapses (folds) block computations into a single expression,
% instead of generating separate code statements and storage declarations
% for each block in a model. Most Simulink blocks support expression
% folding.
% 
% Expression folding improves the efficiency of generated code, frequently
% achieving results that compare favorably to hand-optimized code. In many
% cases, entire groups of model computations fold into a single, highly
% optimized line of code.
%  
%   Copyright 2014 The MathWorks, Inc.

%% Example Model
% 
model = 'rtwdemo_slexprfold';
open_system(model);

%%


%% Generate Code 
% Expression folding is available only when the *Signal storage reuse*
% parameter is set to on because expression folding operates only on
% expressions involving local variables. The *Signal storage reuse* and
% *Eliminate superfluous local variables (expression folding)* parameters are
% on by default. On the *All Parameters* tab, clear the *Eliminate superfluous local variables*
% *(expression folding)* parameter or enter the following command in the
% MATLAB Command Window to turn the parameter off:
%
set_param(model, 'ExpressionFolding','off'); 
%%
% Create a temporary folder for the build and inspection process.
currentDir = pwd;
[~,cgDir] = rtwdemodir();

%%
% Build the model.
rtwbuild(model)

%%
% With expression folding off, in the |rtwdemo_slexprfold.c| file, there
% are separate code statements before and in the Switch block operation.
cfile = fullfile(cgDir,'rtwdemo_slexprfold_grt_rtw','rtwdemo_slexprfold.c');
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize', 1, 0);

%% Generate Code with Optimization
% Enter the following command to turn expression folding on:
set_param(model, 'ExpressionFolding','on');

%%
% Build the model.
rtwbuild(model);

%%
% The following is a portion of rtwdemo_slexprfold.c. In the optimized
% code, the code generator folds all computations into the Switch block
% operation.
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize', 1, 0);

%%
% Close the model and code generation report.
bdclose(model)
rtwdemoclean;
cd(currentDir)