%% Schedule a Subsystem Multiple Times in a Single Step
% This example shows how to design a _loop scheduler_ in Stateflow(R). The
% loop scheduler design pattern enables you to execute a Simulink(R)
% subsystem multiple times in a single time step.

% Copyright 2007-2019 The MathWorks, Inc.

%%
model = 'sf_loop_scheduler';
load_system(model)

% Delete all annotations at the top level of the model
ah = find_system(model, 'FindAll', 'on', 'type', 'annotation');
for i = 1:length(ah)
   ao = get_param(ah(i), 'Object');
   ao.delete;
end

% Update chart
set_param(model,'SimulationCommand','Update')

open_system(model)

%% Key Behavior of the Loop Scheduler
% In this example, the Loop Scheduler chart broadcasts a function-call
% output event to execute the function-call subsystem A1 multiple times
% every time step. During each time step:
%
% # The Simulink model activates the Edge to Function chart at the rising
% edge of the 1-millisecond pulse generator.
% # The Edge to Function chart broadcasts the function-call output event
% |call| to activate the Loop Scheduler chart.
% # The Loop Scheduler chart calls the |<docid:stateflow_ref#send send>|
% operator to broadcast the function-call output event |A1| multiple times.

open_system([model '/Loop Scheduler']);

%%
% Each broadcast of the event |A1| executes the subsystem A1. The subsystem
% computes its output and returns control back to the Loop Scheduler chart.

%% Run the Loop Scheduler
% When you simulate the model, the scope displays the value of |y| at each
% time step. 

sim(model);
open_system([model '/Scope']);

%%
% During each time step, the value of |y| increases by 25 because:
% 
% * The flow chart in the Loop Scheduler implements a |for| loop that
% iterates 10 times.
% * In each iteration of the |for| loop, the chart increments |y| by 1 (the
% constant value of input |u1|).
% * Each time that the chart broadcasts the output event to subsystem A1,
% the subsystem increments |y| by 1.5.
