%% Optimize Generated Code by Combining Multiple |for| Constructs
% This example shows how the code generator combines |for| loops. The generated code uses |for| constructs to represent a variety of modeling patterns, such as a matrix
% signal or Iterator blocks. Using data dependency analysis, the code generator combines |for| constructs
% to reduce static code size and runtime branching.
%
% The benefits of optimizing |for| loops are:
%
% * Reducing ROM and RAM consumption.
% * Increasing execution speed.
%% |for| Loop Modeling Patterns
% In the model, <matlab:rtwdemo_forloop rtwdemo_forloop>, the Switch block
% and MATLAB Function block represent |for| constructs. In the |In1| Block
% Parameters dialog box, the *Port dimensions* parameter is set to |10| .
model = 'rtwdemo_forloop';
open_system(model);

%% Generate Code
% The model does not contain data dependencies across the |for| loop iterations. Therefore, 
% the code generator combines |for| loops into one loop. Open the *Simulink Coder* or *Embedded Coder* app. 
% Then, generate and view the code.
currentDir = pwd;
[~,cgDir] = rtwdemodir();
rtwbuild(model)

%%
% The generated file, |rtwdemo_forloop.c|, contains the code for the single
% |for| loop.
cfile = fullfile(cgDir,'rtwdemo_forloop_grt_rtw','rtwdemo_forloop.c'); 
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize', 1, 0); % Extract code for display

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



%% 
% Copyright 2012-2019 The MathWorks, Inc.