Documentation 
On this page… 

The first phase of simulation occurs when the system's model is open and you simulate the model. In the Simulink^{®} Editor, select Simulation > Run. Running the simulation causes the Simulink engine to invoke the model compiler. The model compiler converts the model to an executable form, a process called compilation. In particular, the compiler:
Evaluates the model's block parameter expressions to determine their values.
Determines signal attributes, e.g., name, data type, numeric type, and dimensionality, not explicitly specified by the model and checks that each block can accept the signals connected to its inputs.
A process called attribute propagation is used to determine unspecified attributes. This process entails propagating the attributes of a source signal to the inputs of the blocks that it drives.
Performs block reduction optimizations.
Flattens the model hierarchy by replacing virtual subsystems with the blocks that they contain (see Solvers).
Determines the block sorted order (see Control and Display the Sorted Order for more information).
Determines the sample times of all blocks in the model whose sample times you did not explicitly specify (see How Propagation Affects Inherited Sample Times).
These events are essentially the same as what occurs when you update a diagram (Update a Block Diagram). The difference is that the Simulink software starts model compilation as part of model simulation, where compilation leads directly into the linking phase, as described in Link Phase. In contrast, you start an explicit model update as a standalone operation on a model.
In this phase, the Simulink engine allocates memory needed for working areas (signals, states, and runtime parameters) for execution of the block diagram. It also allocates and initializes memory for data structures that store runtime information for each block. For builtin blocks, the principal runtime data structure for a block is called the SimBlock. It stores pointers to a block's input and output buffers and state and work vectors.
In the Link phase, the Simulink engine also creates method execution lists. These lists list the most efficient order in which to invoke a model's block methods to compute its outputs. The block sorted order lists generated during the model compilation phase is used to construct the method execution lists.
You can assign update priorities to blocks (see Assign Block Priorities). The output methods of higher priority blocks are executed before those of lower priority blocks. The priorities are honored only if they are consistent with its block sorting rules.
Once the Link Phase completes, the simulation enters the simulation loop phase. In this phase, the Simulink engine successively computes the states and outputs of the system at intervals from the simulation start time to the finish time, using information provided by the model. The successive time points at which the states and outputs are computed are called time steps. The length of time between steps is called the step size. The step size depends on the type of solver (see Solvers) used to compute the system's continuous states, the system's fundamental sample time (see Sample Times in Systems), and whether the system's continuous states have discontinuities (see ZeroCrossing Detection).
The Simulation Loop phase has two subphases: the Loop Initialization phase and the Loop Iteration phase. The initialization phase occurs once, at the start of the loop. The iteration phase is repeated once per time step from the simulation start time to the simulation stop time.
At the start of the simulation, the model specifies the initial states and outputs of the system to be simulated. At each step, new values for the system's inputs, states, and outputs are computed, and the model is updated to reflect the computed values. At the end of the simulation, the model reflects the final values of the system's inputs, states, and outputs. The Simulink software provides data display and logging blocks. You can display and/or log intermediate results by including these blocks in your model.
At each time step, the Simulink engine:
The Simulink engine initiates this step by invoking the Simulink model Outputs method. The model Outputs method in turn invokes the model system Outputs method, which invokes the Outputs methods of the blocks that the model contains in the order specified by the Outputs method execution lists generated in the Link phase of the simulation (see Solvers).
The system Outputs method passes the following arguments to each block Outputs method: a pointer to the block's data structure and to its SimBlock structure. The SimBlock data structures point to information that the Outputs method needs to compute the block's outputs, including the location of its input buffers and its output buffers.
The Simulink engine computes a model's states by invoking a solver. Which solver it invokes depends on whether the model has no states, only discrete states, only continuous states, or both continuous and discrete states.
If the model has only discrete states, the Simulink engine invokes the discrete solver selected by the user. The solver computes the size of the time step needed to hit the model's sample times. It then invokes the Update method of the model. The model Update method invokes the Update method of its system, which invokes the Update methods of each of the blocks that the system contains in the order specified by the Update method lists generated in the Link phase.
If the model has only continuous states, the Simulink engine invokes the continuous solver specified by the model. Depending on the solver, the solver either in turn calls the Derivatives method of the model once or enters a subcycle of minor time steps where the solver repeatedly calls the model's Outputs methods and Derivatives methods to compute the model's outputs and derivatives at successive intervals within the major time step. This is done to increase the accuracy of the state computation. The model Outputs method and Derivatives methods in turn invoke their corresponding system methods, which invoke the block Outputs and Derivatives in the order specified by the Outputs and Derivatives methods execution lists generated in the Link phase.
Optionally checks for discontinuities in the continuous states of blocks.
A technique called zerocrossing detection is used to detect discontinuities in continuous states. See ZeroCrossing Detection for more information.
Steps 1 through 4 are repeated until the simulation stop time is reached.
A dynamic system is simulated by computing its states at successive time steps over a specified time span, using information provided by the model. The process of computing the successive states of a system from its model is known as solving the model. No single method of solving a model suffices for all systems. Accordingly, a set of programs, known as solvers, are provided that each embody a particular approach to solving a model. The Configuration Parameters dialog box allows you to choose the solver most suitable for your model (see Choosing a Solver Type).
The solvers provided in the Simulink software fall into two basic categories: fixedstep and variablestep.
Fixedstep solvers solve the model at regular time intervals from the beginning to the end of the simulation. The size of the interval is known as the step size. You can specify the step size or let the solver choose the step size. Generally, decreasing the step size increases the accuracy of the results while increasing the time required to simulate the system.
Variablestep solvers vary the step size during the simulation, reducing the step size to increase accuracy when a model's states are changing rapidly and increasing the step size to avoid taking unnecessary steps when the model's states are changing slowly. Computing the step size adds to the computational overhead at each step but can reduce the total number of steps, and hence simulation time, required to maintain a specified level of accuracy for models with rapidly changing or piecewise continuous states.
The Simulink product provides both continuous and discrete solvers.
Continuous solvers use numerical integration to compute a model's continuous states at the current time step based on the states at previous time steps and the state derivatives. Continuous solvers rely on the individual blocks to compute the values of the model's discrete states at each time step.
Mathematicians have developed a wide variety of numerical integration techniques for solving the ordinary differential equations (ODEs) that represent the continuous states of dynamic systems. An extensive set of fixedstep and variablestep continuous solvers are provided, each of which implements a specific ODE solution method (see Choosing a Solver Type).
Discrete solvers exist primarily to solve purely discrete models. They compute the next simulation time step for a model and nothing else. In performing these computations, they rely on each block in the model to update its individual discrete states. They do not compute continuous states.
Note You must use a continuous solver to solve a model that contains both continuous and discrete states. You cannot use a discrete solver because discrete solvers cannot handle continuous states. If, on the other hand, you select a continuous solver for a model with no states or discrete states only, Simulink software uses a discrete solver. 
Two discrete solvers are provided: A fixedstep discrete solver and a variablestep discrete solver. The fixedstep solver by default chooses a step size and hence simulation rate fast enough to track state changes in the fastest block in your model. The variablestep solver adjusts the simulation step size to keep pace with the actual rate of discrete state changes in your model. This can avoid unnecessary steps and hence shorten simulation time for multirate models (see Sample Times in Systems for more information).
Some continuous solvers subdivide the simulation time span into major and minor time steps, where a minor time step represents a subdivision of the major time step. The solver produces a result at each major time step. It uses results at the minor time steps to improve the accuracy of the result at the major time step.
Usually the integration step size is only related to the current step size and the current integration error. However, for signals whose derivative changes rapidly, you can obtain a more accurate integration results by including the derivative input information at each time step. To do so, enable the Model Configuration Parameters > Solver > Shape Preservation option.
A variablestep solver dynamically adjusts the time step size, causing it to increase when a variable is changing slowly and to decrease when the variable changes rapidly. This behavior causes the solver to take many small steps in the vicinity of a discontinuity because the variable is rapidly changing in this region. This improves accuracy but can lead to excessive simulation times.
The Simulink software uses a technique known as zerocrossing detection to accurately locate a discontinuity without resorting to excessively small time steps. Usually this technique improves simulation run time, but it can cause some simulations to halt before the intended completion time.
Two algorithms are provided in the Simulink software: Nonadaptive and Adaptive. For information about these techniques, see ZeroCrossing Algorithms.
The Simulink software comes with three models that illustrate zerocrossing behavior: sldemo_bounce_two_integrators, sldemo_doublebounce, and sldemo_bounce.
The sldemo_bounce_two_integrators model demonstrates how excessive zero crossings can cause a simulation to halt before the intended completion time unless you use the adaptive algorithm.
The sldemo_bounce model uses a better model design than sldemo_bounce_two_integrators.
The sldemo_doublebounce model demonstrates how the adaptive algorithm successfully solves a complex system with two distinct zerocrossing requirements.
The Bounce Model with Two Integrators.
At the MATLAB^{®} command prompt, type sldemo_bounce_two_integratorssldemo_bounce_two_integrators to load the example.
Once the block diagram appears, set the Model Configuration Parameters > Solver > Algorithm parameter to Nonadaptive.
Also in the Solver pane, set the Stop time parameter to 20 s.
Run the model. In the Simulink Editor, select Simulation > Run.
After the simulation completes, click the Scope block window to see the results.
You may need to click on Autoscale to view the results in their entirety.
Use the scope zoom controls to closely examine the last portion of the simulation. You can see that the velocity is hovering just above zero at the last time point.
Change the simulation Stop time edit box in the Simulink Editor toolbar to 25 seconds, and run the simulation again.
This time the simulation halts with an error shortly after it passes the simulated 20 second time point.
Excessive chattering as the ball repeatedly approaches zero velocity has caused the simulation to exceed the default limit of 1000 for the number of consecutive zero crossings allowed. Although you can increase this limit by adjusting the Model Configuration Parameters > Solver > Number of consecutive zero crossings parameter. In this case, making that change does not allow the simulation to simulate for 25 seconds.
Also in the Solver pane, from the Algorithm pull down menu, select the Adaptive algorithm.
Run the simulation again.
This time the simulation runs to completion because the adaptive algorithm prevented an excessive number of zero crossings from occurring.
Bounce Model with a SecondOrder Integrator.
At the MATLAB command prompt, type sldemo_doublebouncesldemo_doublebounce to load the example. The model and an animation window open. In the animation window, two balls are resting on two platforms.
In the animation window, click the Nonadaptive button to run the example using the nonadaptive algorithm. This is the default setting used by the Simulink software for all models.
The ball on the right is given a larger initial velocity and has Consequently, the two balls hit the ground and recoil at different times.
The simulation halts after 14 seconds because the ball on the left exceeded the number of zero crossings limit. The ball on the right is left hanging in mid air.
An error message dialog opens. Click OK to close it.
Click on the Adaptive button to run the simulation with the adaptive algorithm.
Notice that this time the simulation runs to completion, even after the ground shifts out from underneath the ball on the left at 20 seconds.
The bounce and doublebounce models show that highfrequency fluctuations about a discontinuity ('chattering') can cause a simulation to prematurely halt.
It is also possible for the solver to entirely miss zero crossings if the solver error tolerances are too large. This is possible because the zerocrossing detection technique checks to see if the value of a signal has changed sign after a major time step. A sign change indicates that a zero crossing has occurred, and the zerocrossing algorithm will then hunt for the precise crossing time. However, if a zero crossing occurs within a time step, but the values at the beginning and end of the step do not indicate a sign change, the solver steps over the crossing without detecting it.
The following figure shows a signal that crosses zero. In the first instance, the integrator steps over the event because the sign has not changed between time steps. In the second, the solver detects change in sign and so detects the zerocrossing event.
Use the following table to prevent excessive zerocrossing errors in your model.
Make this change...  How to make this change...  Rationale for making this change... 

Increase the number of allowed zero crossings  Increase the value of the Number of consecutive zero crossings. option on the Solver pane in the Configuration Parameters dialog box.  This may give your model enough time to resolve the zero crossing. 
Relax the Signal threshold  Select Adaptive from the Algorithm pull down and increase the value of the Signal threshold option on the Solver pane in the Configuration Parameters dialog box.  The solver requires less time to precisely locate the zero crossing. This can reduce simulation time and eliminate an excessive number of consecutive zerocrossing errors. However, relaxing the Signal threshold may reduce accuracy. 
Use the Adaptive Algorithm  Select Adaptive from the Algorithm pull down on the Solver pane in the Configuration Parameters dialog box.  This algorithm dynamically adjusts the zerocrossing threshold, which improves accuracy and reduces the number of consecutive zero crossings detected. With this algorithm you have the option of specifying both the Time tolerance and the Signal threshold. 
Disable zerocrossing detection for a specific block 
 Locally disabling zerocrossing detection prevents a specific block from stopping the simulation because of excessive consecutive zero crossings. All other blocks continue to benefit from the increased accuracy that zerocrossing detection provides. 
Disable zerocrossing detection for the entire model  Select Disable all from the Zerocrossing control pull down on the Solver pane of the Configuration Parameters dialog box.  This prevents zero crossings from being detected anywhere in your model. A consequence is that your model no longer benefits from the increased accuracy that zerocrossing detection provides. 
If using the ode15s solver, consider adjusting the order of the numerical differentiation formulas  Select a value from the Maximum order pull down on the Solver pane of the Configuration Parameters dialog box.  For more information, see Maximum order. 
Reduce the maximum step size  Enter a value for the Max step size option on the Solver pane of the Configuration Parameters dialog box.  This can insure the solver takes steps small enough to resolve the zero crossing. However, reducing the step size can increase simulation time, and is seldom necessary when using the Adaptive algorithm. 
The Simulink software includes two zerocrossing detection algorithms: Nonadaptive and Adaptive.
To choose the algorithm, either use the Algorithm option in the Solver pane of the Configuration Parameter dialog box, or use the ZeroCrossAlgorithm command. The command can either be set to 'Nonadaptive' or 'Adaptive'.
The Nonadaptive algorithm is provided for backwards compatibility with older versions of Simulink and is the default. It brackets the zerocrossing event and uses increasingly smaller time steps to pinpoint when the zero crossing has occurred. Although adequate for many types of simulations, the Nonadaptive algorithm can result in very long simulation times when a high degree of 'chattering' (high frequency oscillation around the zerocrossing point) is present.
The Adaptive algorithm dynamically turns the bracketing on and off, and is a good choice when:
The system contains a large amount of chattering.
You wish to specify a guard band (tolerance) around which the zero crossing is detected.
The Adaptive algorithm turns off zerocrossing bracketing (stops iterating) if either of the following are satisfied:
The zero crossing error is exceeded. This is determined by the value specified in the Signal threshold option in the Solver pane of the Configuration Parameters dialog box. This can also be set with the ZCThreshold command. The default is Auto, but you can enter any real number greater than zero for the tolerance.
The system has exceeded the number of consecutive zero crossings specified in the Number of consecutive zero crossings option in the Solver pane of the Configuration Parameters dialog box. Alternatively, this can be set with the MaxConsecutiveZCs command.
The Adaptive algorithm automatically sets a tolerance for zerocrossing detection. Alternatively, you can set the tolerance by entering a real number greater than or equal to zero in the Configuration Parameters Solver pane, Signal threshold pull down. This option only becomes active when the zerocrossing algorithm is set to Adaptive.
This graphic shows how the Signal threshold sets a window region around the zerocrossing point. Signals falling within this window are considered as being at zero.
The zerocrossing event is bracketed by time steps T_{n1} and T_{n}. The solver iteratively reduces the time steps until the state variable lies within the band defined by the signal threshold, or until the number of consecutive zero crossings equals or exceeds the value in the Configuration Parameters Solver pane, Number of consecutive zero crossings pull down.
It is evident from the figure that increasing the signal threshold increases the distance between the time steps which will be executed. This often results in faster simulation times, but might reduce accuracy.
A block can register a set of zerocrossing variables, each of which is a function of a state variable that can have a discontinuity. The zerocrossing function passes through zero from a positive or negative value when the corresponding discontinuity occurs. The registered zerocrossing variables are updated at the end of each simulation step, and any variable that has changed sign is identified as having had a zerocrossing event.
If any zero crossings are detected, the Simulink software interpolates between the previous and current values of each variable that changed sign to estimate the times of the zero crossings (that is, the discontinuities).
Note: The ZeroCrossing detection algorithm can bracket zerocrossing events only for signals of data type double 
Blocks That Register Zero Crossings. The following table lists blocks that register zero crossings and explains how the blocks use the zero crossings:
Block  Description of Zero Crossing 

One: to detect when the input signal crosses zero in either the rising or falling direction.  
Two: one to detect when the upper threshold is engaged, and one to detect when the lower threshold is engaged.  
One: to detect when the signal equals a constant.  
One: to detect when the signal equals zero.  
Two: one to detect when the dead zone is entered (the input signal minus the lower limit), and one to detect when the dead zone is exited (the input signal minus the upper limit).  
One: If an Enable port is inside of a Subsystem block, it provides the capability to detect zero crossings. See the Enable Subsystem block for details Create an Enabled Subsystem.  
One: to detect when the input signal has a discontinuity in either the rising or falling direction  
One: to detect when the input signal has a discontinuity in either the rising or falling direction  
One or two. If there is no output port, there is only one zero crossing to detect when the input signal hit the threshold value. If there is an output port, the second zero crossing is used to bring the output back to 0 from 1 to create an impulselike output.  
One: to detect when the If condition is met.  
If the reset port is present, to detect when a reset occurs. If the output is limited, there are three zero crossings: one to detect when the upper saturation limit is reached, one to detect when the lower saturation limit is reached, and one to detect when saturation is left.  
One: for each element of the output vector, to detect when an input signal is the new minimum or maximum.  
One: to detect when the specified relation is true.  
One: if the relay is off, to detect the switchon point. If the relay is on, to detect the switchoff point.  
Two: one to detect when the upper limit is reached or left, and one to detect when the lower limit is reached or left.  
SecondOrder Integrator  Five: two to detect when the state x upper or lower limit is reached; two to detect when the state dx/dt upper or lower limit is reached; and one to detect when a state leaves saturation. 
One: to detect when the input crosses through zero.  
One: to detect when the input signal has a discontinuity in either the rising or falling direction  
One: to detect the step time.  
One: to detect when the switch condition occurs.  
One: to detect when the case condition is met.  
One: If a Triggered port is inside of a Subsystem block, it provides the capability to detect zero crossings. See the Triggered Subsystem block for details: Create a Triggered Subsystem.  
Two: one for the enable port and one for the trigger port. See the Triggered and Enabled Subsystem block for details: Create a Triggered and Enabled Subsystem 
Note: Zerocrossing detection is also available for a Stateflow^{®} chart that uses continuoustime mode. See Configure a Stateflow Chart to Update in Continuous Time in the Stateflow documentation for more information. 
Implementation Example: Saturation Block. An example of a Simulink block that registers zero crossings is the Saturation block. Zerocrossing detection identifies these state events in the Saturation block:
The input signal reaches the upper limit.
The input signal leaves the upper limit.
The input signal reaches the lower limit.
The input signal leaves the lower limit.
Simulink blocks that define their own state events are considered to have intrinsic zero crossings. Use the Hit Crossing block to receive explicit notification of a zerocrossing event. See Blocks That Register Zero Crossings for a list of blocks that incorporate zero crossings.
The detection of a state event depends on the construction of an internal zerocrossing signal. This signal is not accessible by the block diagram. For the Saturation block, the signal that is used to detect zero crossings for the upper limit is zcSignal = UpperLimit  u, where u is the input signal.
Zerocrossing signals have a direction attribute, which can have these values:
rising — A zero crossing occurs when a signal rises to or through zero, or when a signal leaves zero and becomes positive.
falling — A zero crossing occurs when a signal falls to or through zero, or when a signal leaves zero and becomes negative.
either — A zero crossing occurs if either a rising or falling condition occurs.
For the Saturation block's upper limit, the direction of the zero crossing is either. This enables the entering and leaving saturation events to be detected using the same zerocrossing signal.
Algebraic Loops in Simulink. An algebraic loop in a Simulink model occurs when a signal loop exists with only direct feedthrough blocks within the loop. Direct feedthrough means that the block output depends on the value of an input port; the value of the input directly controls the value of the output. Nondirectfeedthrough blocks maintain a State variable. Two examples are the Integrator or Unit Delay block.
Some Simulink blocks have input ports with direct feedthrough. The software cannot compute the output of these blocks without knowing the values of the signals entering the blocks at these input ports at the current time step.
Some examples of blocks with direct feedthrough inputs are:
Math Function block
Gain block
Product block
StateSpace block, when the D matrix coefficient is nonzero
Sum block
Transfer Fcn block, when the numerator and denominator are of the same order
ZeroPole block, when the block has as many zeros as poles
Tip To determine if a block has direct feedthrough:

An example of an algebraic loop is the following simple loop. Note that this is not a recommended modeling pattern.
Mathematically, this loop implies that the output of the Sum block is an algebraic variable x_{a} that is constrained to equal the first input u minus x_{a} (for example, x_{a} = u – x_{a}). The solution of this simple loop is x_{a} = u/2.
Mathematical Definition of an Algebraic Loop. Simulink contains a suite of numerical solvers for simulating ordinary differential equations (ODEs), which are systems of equations that you can write as:
$$\dot{x}=f(x,t),$$
x is the state vector and t is the independent time variable.
Some systems of equations contain additional constraints that involve the independent variable and the state vector, but not the derivative of the state vector. Such systems are differential algebraic equations (DAEs), not ODEs.
The term algebraic refers to equations that do not involve any derivatives. You can express DAEs that arise in engineering in a semiexplicit form:
$$\begin{array}{l}\dot{x}=f(x,{x}_{a},t)\\ 0=g(x,{x}_{a},t),\end{array}$$
f and g can be vector functions.
The first equation is the differential equation.
The second equation is the algebraic equation.
The vector of differential variables is x.
The vector of algebraic variables is x_{a}.
In Simulink models, algebraic loops are algebraic constraints. Models with algebraic loops define a system of differential algebraic equations. Simulink does not solve DAEs directly. Simulink solves the algebraic equations (the algebraic loop) numerically for x_{a} at each step of the ODE solver.
The following Simulink modelmodel is equivalent to this system of equations in semiexplicit form:
$$\begin{array}{l}\dot{x}=f(x,{x}_{a},t)={x}_{a}\\ 0=g(x,{x}_{a},t)=x+u2{x}_{a}.\end{array}$$
At each step of the ODE solver, the algebraic loop solver must solve the algebraic constraint for x_{a} before calculating the derivative $$\dot{x}$$.
Meaning of Algebraic Loops in Physical Systems. Algebraic constraints can occur when modeling physical systems, often due to conservation laws, such as conservation of mass and energy. You can also use algebraic constraints to impose design constraints on system responses in a dynamic system.
Choosing a particular coordinate system for a model can also result in an algebraic constraint. In most cases, you can eliminate algebraic loops, as described in Removing Algebraic Loops, to produce an ordinary differential equation (ODE). However, this technique may be too time consuming if you have a large, complex model.
MathWorks^{®} offers the Simscape™ software that extends Simulink by providing tools to model systems that span mechanical, electrical, hydraulic, and other physical domains as physical networks.
Simscape software automatically constructs the differential algebraic equations (DAEs) that characterize the behavior of a Simulink model. These equations are integrated with the rest of the model, and the Simscape software solves the DAEs directly. The variables for the components in the different physical domains are solved simultaneously, thereby avoiding problems with algebraic loops.
If your model contains an algebraic loop:
You cannot generate code for the model.
The Simulink algebraic loop solver might not be able to solve the algebraic loop.
While Simulink is trying to solve the algebraic loop, the simulation might execute slowly.
For most models, the algebraic loop solver is computationally expensive for the first time step. Simulink solves subsequent time steps rapidly because a good starting point for x_{a} is available from the previous time step.
Highlighting Algebraic Loops Using the Algebraic Loop Diagnostic
Highlighting Algebraic Loops Using the ashow Debugger Command
Algebraic Loop Diagnostic. Simulink detects algebraic loops during simulation initialization, for example, when you update your diagram. You can set the Algebraic loop diagnostic to report an error or warning if the software detects any algebraic loops in your model.
In the Configuration Parameters dialog box, on the main Diagnostics pane, set the Algebraic loop parameter as follows.
Setting  Simulation Response 

none  Simulink tries to solve the algebraic loop; reports an error only if the algebraic loop cannot be solved. 
warning  Algebraic loops result in warnings. Simulink tries to solve the algebraic loop; reports an error only if the algebraic loop cannot be solved. 
error  Algebraic loops stop the initialization. 
If you want Simulink to try to solve the loop, select none or warning. If you want to review the loop before Simulink tries to solve the loop, select error.
Highlighting Algebraic Loops Using the Algebraic Loop Diagnostic. To highlight algebraic loops in the Simulink Editor when updating or simulating a model:
Open the sldemo_hydcyl model:
sldemo_hydcylsldemo_hydcyl
Open the Configuration Parameters dialog box by selecting Simulation > Model Configuration Parameters.
On the Diagnostics pane, set the Algebraic loop parameter to error.
If the Simulink software finds an algebraic loop in the model, it should stop the simulation and report an error.
Click OK to save the setting.
Click the Start simulation button.
When Simulink detects an algebraic loop during initialization, the simulation stops. The Diagnostic Viewer displays an error message and lists all the blocks in the model that are part of that algebraic loop.
In the Simulink Editor, the software highlights the blocks and signals that constitute the loop in red.
To restore the diagram to its original colors, close the Diagnostic Viewer.
Close the sldemo_hydcyl model without saving the changes.
In the next section, the ashow debugger command shows that this model actually has two algebraic loops.
Highlighting Algebraic Loops Using the ashow Debugger Command. The Simulink debugger allows you to step through a model simulation. To use the ashow command to highlight algebraic loops:
Open the sldemo_hydcyl model.
By default, the Algebraic loop parameter for this model is set to none.
Start the Simulink debugger. In the Simulink Editor, select Simulation > Debug > Debug Model.
Click the Start/Continue button to start the debugger.
In the MATLAB Command Window, type:
ashow
The software lists the two algebraic loops in the sldemo_hydcyl model and the number of blocks in each algebraic loop.
Found 2 Algebraic loop(s): System number#Algebraic loop id, number of blocks in loop  0#1, 9 blocks in loop  0#2, 4 blocks in loop
To list the blocks in the first algebraic loop, in the MATLAB Command Window, enter the following command:
ashow 0#1
The software opens the Control Valve Flow subsystem in the Valve/Cylinder/Piston/Spring Assembly subsystem, highlights that algebraic loop in the model, and lists the nine blocks in the algebraic loop:
 sldemo_hydcyl/Valve//Cylinder//Piston//Spring Assembly/Control Valve Flow/IC  sldemo_hydcyl/Valve//Cylinder//Piston//Spring Assembly/Control Valve Flow/signed sqrt  sldemo_hydcyl/Valve//Cylinder//Piston//Spring Assembly/Control Valve Flow/Product  sldemo_hydcyl/Valve//Cylinder//Piston//Spring Assembly/laminar flow pressure drop  sldemo_hydcyl/Valve//Cylinder//Piston//Spring Assembly/Sum7  sldemo_hydcyl/Pump/IC  sldemo_hydcyl/Valve//Cylinder//Piston//Spring Assembly/Control Valve Flow/
Sum1 (algebraic variable)  sldemo_hydcyl/Pump/Sum1  sldemo_hydcyl/Pump/leakage (algebraic variable)
In the Simulink debugger, click Close.
At the MATLAB command prompt, press Enter to restore the default MATLAB command prompt.
If Simulink reports an algebraic loop in your model, the algebraic loop solver might be able to solve the loop. If Simulink cannot solve the loop, there are several techniques to eliminate the loop.
The following workflow helps you evaluate what techniques to try to eliminate an algebraic loop. Some of those techniques are described in the following sections.
How the Algebraic Loop Solver Works. When a model contains an algebraic loop, the Simulink software uses a nonlinear solver at each time step to solve the algebraic loop. The solver performs iterations to determine the solution to the algebraic constraint (if possible). As a result, models with algebraic loops can run more slowly than models without algebraic loops.
Simulink uses a dogleg trust region algorithm to solve algebraic loops. The tolerance used is smaller than the ode solver reltol and abstol. This is because Simulink uses the "explicit ODE method" to solve Index1 differential algebraic equations (DAEs).
The algebraic loop solver requires:
One block where the loop solver can break the loop and attempt to solve the loop
Real double signals
The underlying algebraic constraint must be a smooth function
For example, suppose your model has a Sum block with two inputs—one additive, the other subtractive. If you feed the output of the Sum block to one of the inputs, you create an algebraic loop where all of the blocks include direct feedthrough.
The Sum block cannot compute the output without knowing the input. Simulink detects the algebraic loop, and the algebraic loop solver solves the loop using an iterative loop. In the Sum block example, the software computes the correct result as follows:
x_{a}(t) = u(t) / 2.
The algebraic loop solver uses a gradientbased search method, which requires continuous first derivatives of the algebraic constraint that correspond to the algebraic loop. As a result, if the algebraic loop contains discontinuities, the algebraic loop solver might fail.
For more information, see Solving Index1 DAEs in MATLAB and Simulink ^{[1]}
TrustRegion and LineSearch Algorithms in the Algebraic Loop Solver. The Simulink algebraic loop solver uses one of two algorithms to solve algebraic loops: trust region and line search. By default, the algebraic loop solver uses the trustregion algorithm.
If the algebraic loop solver cannot solve the algebraic loop with the trustregion algorithm, try simulating the model using the linesearch algorithm.
To switch to the linesearch algorithm, at the MATLAB command line, enter:
set_param(model_name, 'AlgebraicLoopSolver', 'LineSearch');
To switch back to the trustregion algorithm, at the MATLAB command line, enter:
set_param(model_name, 'AlgebraicLoopSolver', 'TrustRegion');
For more information, see:
Shampine and Reichelt's nleqn.m code
The Fortran program HYBRD1 in the User Guide for MINPACK1 ^{[2]}
Powell's "A Fortran subroutine for solving systems in nonlinear equations," in Numerical Methods for Nonlinear Algebraic Equations^{[3]}
TrustRegion Methods for Nonlinear Minimization in the Optimization Toolbox™ documentation.
Line Search in the Optimization Toolbox documentation.
Limitations of the Algebraic Loop Solver. Algebraic loop solving is an iterative process. The Simulink algebraic loop solver is successful only if the algebraic loop converges to a definite answer. When the loop fails to converge, or converges too slowly, the simulation exits with an error.
The algebraic loop solver cannot solve algebraic loops that contain any of the following:
Blocks with discretevalued outputs
Blocks with nondouble or complex outputs
Discontinuities
Stateflow charts
Algebraic loops can occur in large models when atomic subsystems create feedback loops.
In the following generic model, there are two algebraic loops that involve subsystems.
BlackBox_A —> BlackBox_B —> BlackBox_C —> BlackBox_A
BlackBox_B —> BlackBox_C —> BlackBox_B
When you update this model, Simulink detects the loop BlackBox_A —> BlackBox_B —> BlackBox_C —> BlackBox_A.
Since you do not know the contents of these subsystems, you must break the loops by adding a Unit Delay block outside the subsystems. There are three ways to use the Unit Delay to break these loops:
Add a unit delay between BlackBox_A and BlackBox_C
If you add a unit delay on the feedback signal between the subsystems BlackBox_A and BlackBox_C, you introduce the minimum number of unit delays (1) to the system. By introducing the delay before BlackBox_A, BlackBox_B and BlackBox_C use data from the current time step.
Add a unit delay between BlackBox_B and BlackBox_C
If you add a unit delay between the subsystems BlackBox_B and BlackBox_C, you break the algebraic loop between BlackBox_B and BlackBox_C. In addition, you break the loop between BlackBox_A and BlackBox_C, because that signal completes the algebraic loop. By inserting the Unit Delay block before BlackBox_C, BlackBox_C now works with data from the previous time step only.
Add unit delays to both algebraic loops
In the following example, you insert Unit Delay blocks to break both algebraic loops. In this model, BlackBox_A and BlackBox_B use data from the previous time step. BlackBox_C uses data from the current time step.
If the Simulink software cannot solve the algebraic loop, the software reports an error. If the Simulink algebraic loop solver cannot solve the algebraic loop, use one of the following techniques to solve the loop manually:
Restructure the underlying DAEs using techniques such as differentiation or change of coordinates. These techniques put the DAEs in a form that is easier for the algebraic loop solver to solve.
Convert the DAEs to ODEs, which eliminates any algebraic loops.
Create Initial Guesses Using the IC and Algebraic Constraint Blocks
Create Initial Guesses Using the IC and Algebraic Constraint Blocks. Your model might contain loops for which the loop solver cannot converge without a good, initial guess for the algebraic states. You can specify an initial guess for the algebraic state variables, but use this technique only when you think the loop is legitimate.
There are two ways to specify an initial guess:
Place an IC block in the algebraic loop.
Specify an initial guess for a signal in an algebraic loop using an Algebraic Constraint block.
During the updating phase of simulation, Simulink determines the order in which to execute the block methods during simulation. This block invocation ordering is the sorted order.
If you assign priorities to nonvirtual blocks to indicate to Simulink their execution order relative to other blocks, the algebraic loop solver does not honor these priorities when attempting to solve any algebraic loops.
Eliminating Artificial Algebraic Loops Caused by Atomic Subsystems
Model and Block Parameters for Diagnosing and Eliminating Artificial Algebraic Loops
What Is an Artificial Algebraic Loop?. An artificial algebraic loop occurs when an atomic subsystem or Model block causes Simulink to detect an algebraic loop, even though the contents of the subsystem do not contain an algebraic constraint. When you create an atomic subsystem, all Inport blocks are direct feedthrough, resulting in an algebraic loop.
The following modelmodel does not contain an algebraic loop. The model simulates without error.
Suppose you enclose the Controller and Plant blocks in a subsystem and, in the Subsystem Parameters dialog box, select Treat as atomic unit to make the subsystem atomic.
When simulating this modelmodel, Simulink detects an algebraic loop because the subsystem is direct feedthrough, even though the path within the atomic subsystem is not direct feedthrough.
In the Configuration Parameters dialog box, on the main Diagnostics pane, if you set the Algebraic loop parameter to error, Simulink stops the simulation with an algebraic loop error.
Eliminating Artificial Algebraic Loops Caused by Atomic Subsystems. One way to eliminate an artificial algebraic loop caused by an atomic subsystem is to convert the atomic subsystem to a virtual subsystem. Doing so has no effect on the behavior of the model.
When the subsystem is atomic and you simulate the model, Simulink invokes the algebraic loop solver. The algebraic loop solver terminates after one iteration. The algebraic loop is automatically solved because there is no algebraic constant. After you make the subsystem virtual, during simulation, Simulink does not invoke the algebraic loop solver.
To convert an atomic subsystem to a virtual subsystem:
Open the model that contains the atomic subsystem.
Rightclick the atomic subsystem and select Subsystem Parameters.
Clear the Treat as atomic unit parameter.
Click OK to save the changes and close the dialog box.
Save the model.
If you replace the atomic subsystem with a virtual subsystem and the simulation still fails with an algebraic loop error, you probably have one of the following elsewhere in your model:
An algebraic constraint
An artificial algebraic loop not caused by this atomic subsystem
Examine your model, try to identify the location of the algebraic loop, and use some of the techniques described in this section to solve the loop.
Bundled Signals That Create Artificial Algebraic Loops. Some models bundle signals together. This bundling might cause Simulink to detect an algebraic loop, even when an algebraic constraint does not exist. If you redirect one or more signals, you might remove the artificial algebraic loop.
The following linearized modelmodel simulates the dynamics of a twotank system fed by a single pump. In this model:
Output q1 is the rate of the fluid flow into the tank from the pump.
Output h2 is the height of the fluid in the second tank.
The StateSpace block defines the dynamic response of the tank system to the pump operation:
The output from the StateSpace block is a vector that contains q1 and h2.
If you simulate this modelmodel with the Algebraic loop parameter set to warn or error, Simulink identifies the algebraic loop.
To eliminate this algebraic loop:
Change the C and D matrices as follows:
Pass q1 directly to the Scope instead of through the StateSpace block.
Now, the input (q1) does not pass directly to the output (the D matrix is 0), so the StateSpace block no longer has direct feedthrough. The feedback signal has only one element now, so the Selector block is no longer necessary, as you can see in the following modelmodel.
Model and Block Parameters for Diagnosing and Eliminating Artificial Algebraic Loops. There are two parameters to consider when you think that your model has an artificial algebraic loop:
Minimize algebraic loop occurrences parameter — Specify that Simulink try to eliminate any artificial algebraic loops for:
Atomic subsystems — In the Subsystem Parameters dialog box, select Minimize algebraic loop occurrences.
Model blocks — For the referenced model, in the Configuration Parameters dialog box, on the Model Referencing pane, select Minimize algebraic loop occurrences
Minimize algebraic loop parameter — If the Minimize algebraic loop occurrences parameter has no effect, specifies what diagnostic action Simulink takes.
The Minimize algebraic loop parameter is in the Configuration Parameters dialog box, on the main Diagnostics pane. The diagnostic actions for this parameter are:
Setting  Simulation Response 

none  Simulink takes no action. 
warning  Simulink displays a warning that the Minimize algebraic loop occurrences parameter has no effect. 
error  Simulink terminates the simulation and displays an error that the Minimize algebraic loop occurrences parameter has no effect. 
Block Reduction and Artificial Algebraic Loops. When you enable the Block reduction optimization in the Configuration Parameters dialog box, Simulink collapses certain groups of blocks into a single, more efficient block, or removes them entirely. Enabling block reduction results in faster execution during model simulation and in generated code.
Enabling block reduction may also help Simulink solve artificial algebraic loops.
Consider the following example modelmodel.
Initially, block reduction is turned off. When you simulate this modelmodel, the Atomic Unit subsystem and Gain and Compare to Constant blocks are part of an algebraic loop that Simulink cannot solve.
If you enable block reduction and sorted order, and resimulate the model, Simulink does not display the sorted order for blocks that have been reduced. You can now quickly see which blocks have been reduced.
The Compare to Constant and Gain blocks have been eliminated from the model, so they no longer generate an algebraic loop error. The Atomic Unit subsystem generates a warning:
Warning: If the inport 'ex_aloop_block_reduction_errwarn/ Atomic Unit/In1' of subsystem 'ex_aloop_block_reduction_errwarn/ Atomic Unit' involves direct feedback, then an algebraic loop exists, which Simulink cannot remove. Consider clearing the 'Minimize algebraic loop occurrences' parameter to avoid this warning.
How Simulink Eliminates Artificial Algebraic Loops. When you enable Minimize algebraic loop occurrences, Simulink tries to eliminate artificial algebraic loops. This section describes this process, using this modelmodel, which from contains an atomic subsystem that causes an artificial algebraic loop.
The contents of the atomic subsystem are not direct feedthrough, but Simulink identifies the atomic subsystem as direct feedthrough.
If the Algebraic loop diagnostic is set to error, simulating the model results in an error because the model contains an artificial algebraic loop involving its atomic subsystem.
To see how Simulink tries to eliminate this algebraic loop, follow these steps:
Create the model from the preceding graphics, with the atomic subsystem that causes the artificial algebraic loop.
Select Simulation > Model Configuration Parameters.
In the Configuration Parameters dialog box, on the main Diagnostics pane, set the Algebraic loop parameter to warning or none.
On the Data Import/Export pane, make sure the Signal logging parameter is disabled. If signal logging is enabled, Simulink cannot eliminate artificial algebraic loops.
Click OK.
To display the sorted order for this model and the atomic subsystem, select Display > Blocks > Sorted Execution Order.
Reviewing the sorted order might help you understand how to eliminate the artificial algebraic loop.
All the blocks in the subsystem execute at the same level: 1. (0 is the lowest level, indicating the first blocks to execute.)
Note: For more information about sorted order, see Control and Display the Sorted Order. 
In the toplevel model, rightclick the subsystem and select Subsystem Parameters.
Select Minimize algebraic loop occurrences.
This parameter indicates to Simulink to try to eliminate the algebraic loop that contains the atomic subsystem when it simulates the model.
Click OK.
Click Simulation > Update Diagram to recalculate the sorted order.
Now there are two levels of sorted order inside the subsystem: 1 and 2.
To eliminate the artificial algebraic loop, Simulink tries to make the input of the subsystem or referenced model nondirect feedthrough.
When you simulate a model, all the blocks first execute their mdlOutputs method, and then their mdlDerivatives and mdlUpdate methods.
In the original version of this modelmodel, the execution of the mdlOutputs method starts with the Plant block because the Plant block is nondirect feedthrough. The execution finishes with the Controller block.
Note: For more information about these methods, see Block Methods. 
If you enable the Minimize algebraic loop occurrences parameter for the atomic subsystem, Simulink divides the subsystem into two atomic units.
The following conditions are true:
Atomic unit 2 is not direct feedthrough.
Atomic unit 1 has only a mdlOutputs method.
The output of Atomic unit 1 is needed only by the mdlDerivatives or mdlUpdate methods of Atomic unit 2. Simulink can execute what normally would have been executed during the mdlOutput method of Atomic unit 1 in the mdlDerivatives methods of Atomic unit 2.
The new execution order for the model is:
mdlOutputs method of model
mdlOutputs method of Atomic unit 2
mdlOutputs methods of other blocks
mdlDerivatives method of model
mdlOutputs method of Atomic unit 1
mdlDerivatives method of Atomic unit 2
mdlDerivatives method of other blocks
For the Minimize algebraic loop occurrences technique to be successful, the subsystem or referenced model must have a nondirectfeedthrough block connected directly to an Inport. Simulink can then set the DirectFeedthrough property of the block Inport to false to indicate that the input port does not have direct feedthrough.
When Simulink Cannot Eliminate Artificial Algebraic Loops. Setting the Minimize algebraic loop occurrences parameter does not always work. Simulink cannot change the DirectFeedthrough property of an Inport for an atomic subsystem if the Inport is connected to an Outport only through directfeedthrough blocks.
Consider the following modelmodel. The subsystem Plant+Controller causes an algebraic loop, but it has an extra Gain block and an extra output.
Simulink cannot move the mdlOutputs method of the Controller block to the mdlDerivative method of an Atomic unit 1 because the output of the atomic subsystem depends on the output of the Controller block. You cannot make the subsystem nondirectfeedthrough.
You can modify this model to eliminate the artificial algebraic loop by redefining the atomic subsystem by adding additional Inport and Gain blocks, as you can see in the following modelmodel. Doing so makes In1 nondirectfeedthrough and In2 direct feedthrough, breaking the algebraic loop.
Managing Large Models with Artificial Algebraic Loops. For large models with algebraic loops, MathWorks recommends the following techniques:
Avoid creating loops that contain discontinuities or nondouble data types. The Simulink algebraic loop solver is gradientbased and must solve algebraic constraints to high precision.
Develop a scheme for clearly identifying atomic subsystems as direct feedthrough or not direct feedthrough. Use a visual scheme such as coloring the blocks or defining a blocknaming convention.
If you plan to generate code for your model, enable the Minimize algebraic loop occurrences parameter for all atomic subsystems. When possible, make sure that the input ports for the atomic subsystems are connected directly to nondirectfeedthrough blocks.
Avoid combining nondirectfeedthrough and directfeedthrough paths using the Bus Creator or Mux blocks. Simulink might not be able to eliminate any resulting artificial algebraic loops. Instead, consider clustering the nondirectfeedthrough and directfeedthrough objects in separate subsystems.
Use Bus Selector blocks to pass only the required signals into atomic subsystems.
^{[1] }Shampine, Lawrence F., M.W.Reichelt, and J.A.Kierzenka. "Solving Index1 DAEs in MATLAB and Simulink."Siam Review.Vol.18,No.3,1999,pp.538–552.
^{[2] }More,J.J.,B.S.Garbow, and K.E.Hillstrom. User guide for MINPACK1. Argonne, IL:Argonne National Laboratory,1980.
^{[3] }Rabinowitz, Philip, ed. Numerical Methods for Nonlinear Algebraic Equations, New York: Gordon and Breach Science Publishers, 1970.