Documentation Center

  • Trials
  • Product Updates

Simulating Dynamic Systems

Model Compilation

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.

Link Phase

In this phase, the Simulink engine allocates memory needed for working areas (signals, states, and run-time parameters) for execution of the block diagram. It also allocates and initializes memory for data structures that store run-time information for each block. For built-in blocks, the principal run-time 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.

Method Execution Lists

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.

Block Priorities

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.

Simulation Loop Phase

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 Zero-Crossing 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.

Loop Iteration

At each time step, the Simulink engine:

  1. Computes the model's outputs.

    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.

  2. Computes the model's states.

    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.

  3. Optionally checks for discontinuities in the continuous states of blocks.

    A technique called zero-crossing detection is used to detect discontinuities in continuous states. See Zero-Crossing Detection for more information.

  4. Computes the time for the next time step.

Steps 1 through 4 are repeated until the simulation stop time is reached.

Solvers

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).

Fixed-Step Solvers Versus Variable-Step Solvers

The solvers provided in the Simulink software fall into two basic categories: fixed-step and variable-step.

Fixed-step 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.

Variable-step 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.

Continuous Versus Discrete Solvers

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 fixed-step and variable-step 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 fixed-step discrete solver and a variable-step discrete solver. The fixed-step 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 variable-step 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).

Minor Time Steps

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.

Shape Preservation

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.

Zero-Crossing Detection

A variable-step 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 zero-crossing 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 Zero-Crossing Algorithms.

Demonstrating Effects of Excessive Zero-Crossing Detection

The Simulink software comes with three models that illustrate zero-crossing 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 zero-crossing requirements.

The Bounce Model with Two Integrators.  

  1. At the MATLAB® command prompt, type sldemo_bounce_two_integratorssldemo_bounce_two_integrators to load the example.

  2. Once the block diagram appears, set the Model Configuration Parameters > Solver > Algorithm parameter to Nonadaptive.

  3. Also in the Solver pane, set the Stop time parameter to 20 s.

  4. Run the model. In the Simulink Editor, select Simulation > Run.

  5. 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.

  6. 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.

  7. Change the simulation Stop time edit box in the Simulink Editor toolbar to 25 seconds, and run the simulation again.

  8. 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.

  9. Also in the Solver pane, from the Algorithm pull down menu, select the Adaptive algorithm.

  10. Run the simulation again.

  11. This time the simulation runs to completion because the adaptive algorithm prevented an excessive number of zero crossings from occurring.

Bounce Model with a Second-Order Integrator.  

The Double-Bounce Model.  

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. An error message dialog opens. Click OK to close it.

  6. Click on the Adaptive button to run the simulation with the adaptive algorithm.

  7. 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.

How the Simulator Can Miss Zero-Crossing Events

The bounce and double-bounce models show that high-frequency 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 zero-crossing 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 zero-crossing 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 zero-crossing event.

Preventing Excessive Zero Crossings

Use the following table to prevent excessive zero-crossing 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 zero-crossing 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 zero-crossing 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 zero-crossing detection for a specific block

  1. Clear the Enable zero-crossing detection check box on the block's parameter dialog box.

  2. Select Use local settings from the Zero-crossing control pull down on the Solver pane of the Configuration Parameters dialog box.

Locally disabling zero-crossing 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 zero-crossing detection provides.

Disable zero-crossing detection for the entire model

Select Disable all from the Zero-crossing 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 zero-crossing 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.

Zero-Crossing Algorithms

The Simulink software includes two zero-crossing 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 zero-crossing 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 zero-crossing 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 zero-crossing 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.

Understanding Signal Threshold

The Adaptive algorithm automatically sets a tolerance for zero-crossing 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 zero-crossing algorithm is set to Adaptive.

This graphic shows how the Signal threshold sets a window region around the zero-crossing point. Signals falling within this window are considered as being at zero.

The zero-crossing event is bracketed by time steps Tn-1 and Tn. 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.

How Blocks Work with Zero-Crossing Detection

A block can register a set of zero-crossing variables, each of which is a function of a state variable that can have a discontinuity. The zero-crossing function passes through zero from a positive or negative value when the corresponding discontinuity occurs. The registered zero-crossing variables are updated at the end of each simulation step, and any variable that has changed sign is identified as having had a zero-crossing 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 Zero-Crossing detection algorithm can bracket zero-crossing 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:

BlockDescription of Zero Crossing

Abs

One: to detect when the input signal crosses zero in either the rising or falling direction.

Backlash

Two: one to detect when the upper threshold is engaged, and one to detect when the lower threshold is engaged.

Compare To Constant

One: to detect when the signal equals a constant.

Compare To Zero

One: to detect when the signal equals zero.

Dead Zone

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).

Enable

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.

From File

One: to detect when the input signal has a discontinuity in either the rising or falling direction

From Workspace

One: to detect when the input signal has a discontinuity in either the rising or falling direction

Hit Crossing

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 impulse-like output.

If

One: to detect when the If condition is met.

Integrator

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.

MinMax

One: for each element of the output vector, to detect when an input signal is the new minimum or maximum.

Relational Operator

One: to detect when the specified relation is true.

Relay

One: if the relay is off, to detect the switch-on point. If the relay is on, to detect the switch-off point.

Saturation

Two: one to detect when the upper limit is reached or left, and one to detect when the lower limit is reached or left.

Second-Order 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.

Sign

One: to detect when the input crosses through zero.

Signal Builder

One: to detect when the input signal has a discontinuity in either the rising or falling direction

Step

One: to detect the step time.

Switch

One: to detect when the switch condition occurs.

Switch Case

One: to detect when the case condition is met.

Trigger

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.

Enabled and 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

Implementation Example: Saturation Block.  An example of a Simulink block that registers zero crossings is the Saturation block. Zero-crossing 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 zero-crossing 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 zero-crossing 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.

Zero-crossing 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 zero-crossing signal.

Algebraic Loops

What Is an Algebraic Loop?

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. Non-direct-feedthrough 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:

    Tip   To determine if a block has direct feedthrough:

    1. Double-click the block.

      The block parameter dialog box opens.

    2. Click the Help button in the block parameter dialog box.

      The block reference page opens.

    3. Scroll to the Characteristics section of the block reference page, which lists whether or not that 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 xa that is constrained to equal the first input u minus xa (for example, xa = uxa). The solution of this simple loop is xa = 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:

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 semi-explicit form:

  • 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 xa.

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 xa at each step of the ODE solver.

The following Simulink modelmodel is equivalent to this system of equations in semi-explicit form:

At each step of the ODE solver, the algebraic loop solver must solve the algebraic constraint for xa before calculating the derivative .

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.

Problems Caused by 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 xa is available from the previous time step.

Identifying Algebraic Loops in Your Model

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:

  1. Open the sldemo_hydcyl model:

    sldemo_hydcylsldemo_hydcyl
  2. Open the Configuration Parameters dialog box by selecting Simulation > Model Configuration Parameters.

  3. 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.

  4. Click OK to save the setting.

  5. 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.

  6. To restore the diagram to its original colors, close the Diagnostic Viewer.

  7. 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:

  1. Open the sldemo_hydcyl model.

    By default, the Algebraic loop parameter for this model is set to none.

  2. Start the Simulink debugger. In the Simulink Editor, select Simulation > Debug > Debug Model.

  3. Click the Start/Continue button to start the debugger.

  4. 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
  5. 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)
  6. In the Simulink debugger, click Close.

  7. At the MATLAB command prompt, press Enter to restore the default MATLAB command prompt.

What If I Have an Algebraic Loop in My Model?

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.

Simulink Algebraic Loop Solver

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 Index-1 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:

xa(t) = u(t) / 2.

The algebraic loop solver uses a gradient-based 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 Index-1 DAEs in MATLAB and Simulink [1]

Trust-Region and Line-Search 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 trust-region algorithm.

If the algebraic loop solver cannot solve the algebraic loop with the trust-region algorithm, try simulating the model using the line-search algorithm.

To switch to the line-search algorithm, at the MATLAB command line, enter:

set_param(model_name, 'AlgebraicLoopSolver', 'LineSearch');

To switch back to the trust-region algorithm, at the MATLAB command line, enter:

set_param(model_name, 'AlgebraicLoopSolver', 'TrustRegion');

For more information, see:

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 discrete-valued outputs

  • Blocks with nondouble or complex outputs

  • Discontinuities

  • Stateflow charts

Removing Algebraic Loops

Introducing a Delay.  

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.

Additional Techniques to Help the Algebraic Loop Solver

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:

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.

Changing Block Priorities Does Not Remove Algebraic Loops

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.

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:

  1. Open the model that contains the atomic subsystem.

  2. Right-click the atomic subsystem and select Subsystem Parameters.

  3. Clear the Treat as atomic unit parameter.

  4. Click OK to save the changes and close the dialog box.

  5. 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 two-tank 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 State-Space block defines the dynamic response of the tank system to the pump operation:

  • The output from the State-Space 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:

  1. Change the C and D matrices as follows:

  2. Pass q1 directly to the Scope instead of through the State-Space block.

    Now, the input (q1) does not pass directly to the output (the D matrix is 0), so the State-Space 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.

    Tip   Use Bus Selector blocks to pass only the required signals into atomic subsystems.

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:

  1. Create the model from the preceding graphics, with the atomic subsystem that causes the artificial algebraic loop.

  2. Select Simulation > Model Configuration Parameters.

  3. In the Configuration Parameters dialog box, on the main Diagnostics pane, set the Algebraic loop parameter to warning or none.

  4. 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.

  5. Click OK.

  6. 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.)

  7. In the top-level model, right-click the subsystem and select Subsystem Parameters.

  8. 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.

  9. Click OK.

  10. 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 non-direct 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 non-direct 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 non-direct-feedthrough 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 direct-feedthrough 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 non-direct-feedthrough.

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 non-direct-feedthrough 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 gradient-based 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 block-naming 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 non-direct-feedthrough blocks.

  • Avoid combining non-direct-feedthrough and direct-feedthrough paths using the Bus Creator or Mux blocks. Simulink might not be able to eliminate any resulting artificial algebraic loops. Instead, consider clustering the non-direct-feedthrough and direct-feedthrough 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 Index-1 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 MINPACK-1. Argonne, IL:Argonne National Laboratory,1980.

[3] Rabinowitz, Philip, ed. Numerical Methods for Nonlinear Algebraic Equations, New York: Gordon and Breach Science Publishers, 1970.

Was this topic helpful?