%% Using Simulink(R) Functions in Stateflow(R)
% This model shows a simple use of Simulink functions in Stateflow.
% Starting from R2008b, you can use Simulink function call subsystems in
% Stateflow just like other function objects such as Graphical functions,
% MATLAB(R) functions and Truth Table functions.

% Copyright 2009-2015 The MathWorks, Inc.

clear
close all
bdclose all

open_system('sf_slalgo');
r = sfroot;
m = r.find('-isa', 'Stateflow.Machine', 'Name', 'sf_slalgo');

c_with = m.find('-isa', 'Stateflow.Chart', 'Name', 'WithSLFunctions');
c_without = m.find('-isa', 'Stateflow.Chart', 'Name', 'WithoutSLFunctions');

% first close all charts.
c_with.Visible = 0;
c_without.Visible = 0;
close_system('sf_slalgo/WithoutSLFunctions');

%% 
% *With Simulink functions*
% 
% The chart |WithSimulinkFunctions| shows the use of Simulink
% functions algo1() and algo2() directly within Stateflow.

c_with.Visible = 1;

%%
% Note the following:
% 
% # We can use multiple outputs syntax to communicate multiple
% outputs/inputs to the Simulink subsystem.
% # Using C as the action language, you can call a Simulink Function
% directly from a Stateflow expression.

%% 
% *Without Simulink functions*
% 
% The chart |WithoutSimulinkFunctions| shows how a similar functionality
% would have been achieved without the use of Simulink functions in
% previous releases.

open_system('sf_slalgo/WithoutSLFunctions');

%% 
c_without.Visible = 1;

%%
% Note the following:
% 
% # You need to create multiple function call output events in order to
% communicate with the Simulink subsystems.
% # You have to manually connect up the inputs/outputs from the Simulink
% subsystems to the Stateflow chart.
% # You cannot use the output from a Simulink subsystem directly in an
% expression. You have to first write to the corresponding outputs,
% |send()| the output event, and then read back from the corresponding
% inputs.
% 
% *Advantages of using Simulink functions*
% 
% Directly using Simulink functions in Stateflow rather than using function
% call output events has several advantages:
% 
% # It is less error-prone since there is much less wiring.
% # Using C as the action language, you can call a Simulink Function
% directly from a Stateflow expression.
% # The design hierarchy is much more evident when the Stateflow chart
% contains the Simulink subsystems which it uses.

bdclose all;
clear
close all;
