%% Avoid Algebraic Loop Errors from Persistent Variables inside MATLAB Function Blocks

% Copyright 2019 The MathWorks, Inc.

%% Guideline ID
% |2.8.2|

%% Severity
% _Mandatory_

%% Description
% When your Simulink(R) model contains MATLAB Function blocks inside a feedback
% loop and uses persistent variables, compiling or simulating the model might
% generate algebraic loop errors. To simulate the model and generate HDL
% code, use nondirect feedthrough.
%
% In certain cases, the persistent delay in
% the MATLAB Function block inside a feedback loop causes an algebraic loop
% error. When you use direct feedthrough, the output of the block
% directly depends on the input. When *Allow direct feedthrough* is cleared,
% the output of the block depends on the internal state and properties and
% does not depend on the input. The nondirect feedthrough semantics
% prevents algebraic loops errors by making the outputs depend only on the state.
%
% For an example, open the model |hdlcoder_MLFB_avoid_algebraic_loops|.
%%
modelname = 'hdlcoder_MLFB_avoid_algebraic_loops';
blkname = 'hdlcoder_MLFB_avoid_algebraic_loops/Subsystem_AlgLoop_Issue/MATLAB Function1';
open_system(modelname)
%%
% When you simulate the model, the algebraic loop error message is
% displayed. The MATLAB Function block
% |hdlcoder_MLFB_avoid_algebraic_loops/Subsystem_AlgLoop_Issue/MATLAB
% Function| uses a persistent variable inside a MATLAB Function block.
open_system(blkname)
%%
% <<../persistent_MLFB_alg_loop.png>>
%
% To avoid this error, use nondirect feedthrough. To specify nondirect
% feedthrough at the command line, create a |MATLABFunctionConfiguration|
% object by using |get_param| function, and then change the property value
% |AllowDirectFeedthrough|:
MLFBConfig = get_param(blkname, 'MATLABFunctionConfiguration');
MLFBConfig.AllowDirectFeedthrough = 0; 
%%
% See also <docid:simulink_ref#mw_4b11d31c-2507-4c83-b069-e6646b8b516c
% MATLABBFunctionConfiguration>.
%%
% To specify nondirect feedthrough from the UI:
%
% # Open the MATLAB Function block |MATLAB Function1|.
% # Opens the Ports and Data Manager dialog box. On the MATLAB(R) Editor, 
% click *Edit Data*. 
% # On the Ports and Data Manager dialog box, clear *Allow direct feedthrough* 
% check box. 
%
% See also <docid:simulink_ug#bvbncuo Prevent Algebraic Loop Errors in 
% MATLAB Function and Stateflow Blocks>.
%
% The model now simulates without algebraic errors. You can now generate 
% HDL code for the Subsystem block |Subsystem_AlgLoop_Issue|.
open_system(modelname)
set_param('hdlcoder_MLFB_avoid_algebraic_loops', 'SimulationCommand', 'Update')
makehdl('hdlcoder_MLFB_avoid_algebraic_loops/Subsystem_AlgLoop_Issue')