%% Schedule Multiple Subsystems in a Single Step
% This example shows how to design a _ladder logic scheduler_ in
% Stateflow(R). The ladder logic scheduler design pattern allows you to
% specify the order in which multiple Simulink(R) subsystems execute in a
% single time step. 

% Copyright 2007-2019 The MathWorks, Inc.

%%
model = 'sf_ladder_logic_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 Ladder Logic Scheduler
% In this example, the Ladder Logic Scheduler chart broadcasts a series of
% function-call output events to execute three function-call subsystems
% (A1, A2, and A3). 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 Ladder Logic Scheduler chart.
% # The Ladder Logic Scheduler chart uses sequencing ladder logic to
% broadcast function-call output events based on the values of the input
% signals |u1| and |u2|.

open_system([model '/Ladder Logic Scheduler']);

%% 
% The chart evaluates each condition sequentially. When a condition is
% valid, the chart calls the |<docid:stateflow_ref#send send>| operator to
% broadcast an output event. The corresponding subsystem computes its
% output and returns control back to the Ladder Logic Scheduler chart.

%% Run the Ladder Logic Scheduler
% When you simulate the model, the scope shows the input and output of each
% function-call subsystem.

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

%%
% During each time step, the Ladder Logic Scheduler chart executes the
% subsystems depending on the values of the input signals |u1| and |u2|:
%
% # If |u1| is positive, the chart sends a function-call output event to
% execute subsystem A1. This subsystem multiplies the value of |u1| by a
% gain of 3 and passes this value back to the Ladder Logic Scheduler chart
% as input |u2|. Control returns to the next condition in the Ladder Logic
% Scheduler chart.
% # If |u2| is greater than 1, the chart sends a function-call output event
% to execute subsystem A2. This subsystem decreases the value of |u2| by 1.
% Control returns to the final condition in the Ladder Logic Scheduler
% chart.
% # If |u2| is less than 2, the chart sends a function-call output event to
% execute subsystem A3. This subsystem multiplies its input by a gain of 2.
%
% In the scope, horizontal segments indicate time steps when a subsystem
% does not execute.