| Simulink® | ![]() |
| On this page… |
|---|
The first phase of simulation occurs when you choose Start from the Model Editor's Simulation menu, with the system's model open. This 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 Controlling and Displaying 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 Sample Time Propagation).
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.
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 Assigning 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 Modeling and Simulating Discrete 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.
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 zero-crossing detection is used to detect discontinuities in continuous states. See Zero-Crossing 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: 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.
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 from the states at previous time steps and the state derivatives. Continuous solvers rely on the model's 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 implementing 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. They do not compute continuous states and they rely on the model's blocks to update the model's discrete states.
Note You can use a continuous solver, but not a discrete solver, to solve a model that contains both continuous and discrete states. This is because a discrete solver does not handle continuous states. If you select a discrete solver for a continuous model, your selection is disregarded and uses a continuous solver instead when solving the model. |
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 Determining Step Size for Discrete 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 who's derivative changes rapidly more accurate integration results can be obtained by including the derivative input information at each time step. This is done by activating the State Shapes Preservation option in the Solver pane of the Configuration Parameter dialog.
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: Non-Adaptive and Adaptive. For information about these techniques, see Zero Crossing Algorithms.
The Simulink software comes with two demos that illustrate zero crossing behavior.
Run the bounce demo to see how excessive zero crossings can cause a simulation to halt before the intended completion time.
Run the doublebounce demo to see how the adaptive algorithm successfully solves a complex system with two distinct zero crossing requirements.
Load the demo by typing bounce at the MATLAB® command prompt.
Once the block diagram appears, navigate to the Configuration Parameters dialog. Confirm that the Zero crossing location algorithm is set to Non-adaptive.
Run the model for a simulation time of 20 seconds.
After the simulation completes, click on the scope to display the results.
You may need to click on Autoscale to get a clear display.
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 run time 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 this limit can be increased by adjusting the Number of consecutive zero crossings allowed parameter in the Configuration Parameters dialog, doing so in this case does not allow the simulation to simulate for 25 seconds.
Navigate to the Configuration Parameters dialog and select the Adaptive zero crossing location algorithm from the Zero crossing location algorithm pull down.
Change the simulation time to 25 seconds, and run the simulation again.
This time the simulation runs to completion because the adaptive algorithm prevented an excessive number of zero crossings from occurring.
Load the demo by typing doublebounce at the MATLAB command prompt.
In the demo, click the Non-adaptive button. This causes the demo to run with the Non-adaptive zero crossing location algorithm. This is the default setting used by the Simulink software for all models.
Notice that the two balls hit the ground and recoil at different times.
The simulation halts after 14 seconds because the ball on the left has exceeded the number of zero crossings limit. The ball on the right is left hanging in mid air.
Click on the error message to clear it.
Click on the Adaptive button to run the simulation with the Adaptive zero crossing location algorithm.
Notice that this time the simulation runs to completion, even when the ground shifts out from underneath the ball on the left after 20 seconds.
The bounce and doublebounce demos 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.

Use this table to help you prevent excessive zero crossing errors in your model.
| Make this change... | How to make this change... | Rational for making this change... |
|---|---|---|
Increase the number of allowed zero crossings | Increase the value of the Number of consecutive zero crossings allowed. option on the Solver pane in the Configuration Parameters dialog. | This may give your model enough time to resolve the zero crossing. |
Relax the zero crossing threshold | Decrease the value of the Consecutive zero crossings relative tolerance option on the Solver pane in the Configuration Parameters dialog. | The solver requires less time to precisely locate the zero crossing. This can reduce simulation time and eliminate excessive number of consecutive zero crossings errors. However, relaxing the zero crossing threshold may reduce accuracy. |
Use the Adaptive Zero crossing location algorithm | Select Adaptive from the Zero crossing location algorithm pull down on the Solver pane in the Configuration Parameters dialog. | 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 a zero crossing tolerance |
Disable zero-crossing detection for a specific block |
| 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 od15s solver, consider adjusting the order of the numerical differentiation formulas | Select a value from the Maxim order pulldown in 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 in 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 zero crossing detection algorithms: Non-Adaptive and Adaptive.
To choose the algorithm, either use the Zero crossing location algorithm option in the Solver pane of the Configuration Parameter dialog, or use the ZeroCrossAlgorithm command. The command can either be set to 'Non-adaptive' or 'Adaptive'.
The Non-Adaptive 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 Non-Adaptive 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 Zero crossing location threshold option in the Solver pane of the Configuration Parameter dialog. This can also be set with the ZcDetectionTol 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 allowed option in the Solver pane of the Configuration Parameter dialog. Alternatively, this can be set with the MaxConsecutiveZCs command.
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, Zero crossing location threshold pull down. This option only becomes active when the Zero crossing algorithm is set to Adaptive.
This graphic shows how the Zero crossing 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 zero crossing threshold, or until the number of consecutive zero crossings equals or exceeds the value in the Configuration Parameters Solver pane, Number of consecuitive zero crossings allowed pull down.
It is evident from the figure that increasing the zero crossing threshold increases the distance between the time steps which will be executed. This often results in faster simulation times, but could reduce accuracy.
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).
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 signals 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: to detect when the input signal has a discontinuity in either the rising or falling direction | |
One: to detect when the input crosses the threshold. | |
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: if the relay is off, to detect the switch on point. If the relay is on, to detect the switch off point. | |
One: to detect when the output changes. | |
Two: one to detect when the upper limit is reached or left, and one to detect when the lower limit is reached or left. | |
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 if there is a valid state transition | |
One: to detect the step time. | |
For conditionally executed subsystems: one for the enable port if present, and one for the trigger port, if present. | |
One: to detect when the switch condition occurs. | |
One: to detect when the case condition is met. |
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.
Some Simulink blocks have input ports with direct feedthrough. This means that the output of these blocks cannot be computed without knowing the values of the signals entering the blocks at these input ports. Some examples of blocks with direct feedthrough inputs are as follows:
Math Function block
Gain block
Integrator block's initial condition ports
Product block
State-Space block when there is a nonzero D matrix
Sum block
Transfer Fcn block when the numerator and denominator are of the same order
Zero-Pole block when there are as many zeros as poles
An algebraic loop generally occurs when an input port with direct feedthrough is driven by the output of the same block, either directly, or by a feedback path through other blocks with direct feedthrough. An example of an algebraic loop is this simple scalar loop.

Mathematically, this loop implies that the output of the Sum block is an algebraic state z constrained to equal the first input u minus z (i.e., z = u - z). The solution of this simple loop is z = u/2, but most algebraic loops cannot be solved by inspection.
It is easy to create vector algebraic loops with multiple algebraic state variables z1, z2, etc., as shown in this model.

The Algebraic Constraint block is a convenient way to model algebraic equations and specify initial guesses. The Algebraic Constraint block constrains its input signal F(z) to zero and outputs an algebraic state z. This block outputs the value necessary to produce a zero at the input. The output must affect the input through some direct feedback path, i.e., the feedback path solely contains blocks with direct feedthrough. You can provide an initial guess of the algebraic state value in the block's dialog box to improve algebraic loop solver efficiency.
A scalar algebraic loop represents a scalar algebraic equation or constraint of the form F(z) = 0, where z is the output of one of the blocks in the loop and the function F consists of the feedback path through the other blocks in the loop to the input of the block. In the simple one-block example shown on the previous page, F(z) = z - (u - z). In the vector loop example shown above, the equations are
z2 + z1 - 1 = 0 z2 - z1 - 1 = 0
Algebraic loops arise when a model includes an algebraic constraint F(z) = 0. This constraint might arise as a consequence of the physical interconnectivity of the system you are modeling, or it might arise because you are specifically trying to model a differential/algebraic system (DAE).
When a model contains an algebraic loop, a loop solving routine is called at each time step. The loop solver performs iterations to determine the solution to the problem (if it can). As a result, models with algebraic loops run slower than models without them.
To solve F(z) = 0, the Simulink loop solver uses Newton's method with weak line search and rank-one updates to a Jacobian matrix of partial derivatives. Although the method is robust, it is possible to create loops for which the loop solver will not converge without a good initial guess for the algebraic states z. You can specify an initial guess for a line in an algebraic loop by placing an IC block (which is normally used to specify an initial condition for a signal) on that line. As shown above, another way to specify an initial guess for a line in an algebraic loop is to use an Algebraic Constraint block.
Whenever possible, use an IC block or an Algebraic Constraint block to specify an initial guess for the algebraic state variables in a loop.
You can highlight algebraic loops when you update, simulate, or debug a model. Use the ashow command to highlight algebraic loops when debugging a model.
To cause Simulink to highlight algebraic loops that it detects when updating or simulating a model, set the Algebraic loop diagnostic on the Diagnostics pane of the Configuration Parameters dialog box to Error (see Configuration Parameters Dialog Box for more information). This causes an error dialog (the Diagnostics Viewer) to be displayed, and portions of the diagram that represent the algebraic loops that have been detected are recolored. Red is used to color the blocks and lines that constitute the loops. Closing the error dialog restores the diagram to its original colors.
For example, the following figure shows the block diagram of the hydcyl demo model in its original colors.

The following figure shows the diagram after updating when the Algebraic loop diagnostic is set to Error.

In this example, Simulink has colored the algebraic loop red, making it stand out from the rest of the diagram.
The Simulink software can eliminate some algebraic loops that include any of the following types of blocks:
To enable automatic algebraic loop elimination for a loop involving a particular instance of an Atomic Subsystem or Enabled Subsystem block, select the Minimize algebraic loop occurrences parameter on the block's parameters dialog box. To enable algebraic loop elimination for a loop involving a Model block, select the Minimize algebraic loop occurrences parameter on the Model Referencing Pane of the Configuration Parameters dialog box (see Model Referencing Pane) of the model referenced by the Model block. If a loop includes more than one instance of these blocks, you should enable algebraic loop elimination for all of them, including nested blocks.
Note The Simulink software does not minimize algebraic loops on signals that are test points, even if you select Minimize algebraic loop occurrences |
Algebraic loop minimization is off by default because it is incompatible with conditional input branch optimization in Simulink (see Optimization Pane ) and with single output/update function optimization in Real-Time Workshop®. If you need these optimizations for an atomic or enabled subsystem or referenced model involved in an algebraic loop, you must eliminate the algebraic loop yourself.
The Minimize algebraic loop solver diagnostic allows you to specify the action Simulink should take, for example, display a warning, if it is unable to eliminate an algebraic loop involving a block for which algebraic loop elimination is enabled. See Diagnostics Pane: Solver for more information.
As an example of the ability of the Simulink software to eliminate algebraic loops, consider the following model.

Simulating this model with the solver's Algebraic Loop diagnostic set to error (see Diagnostics Pane: Solver for more information) reveals that this model contains an algebraic loop involving its atomic subsystem.

Checking the atomic subsystem's Minimize algebraic loop occurrences parameter eliminates the algebraic loop from the compiled version of the model.

As a result, the model now simulates without error.

Note that the Simulink software is able to eliminate the algebraic loop involving this model's atomic subsystem because the atomic subsystem contains a block with a port that does not have direct feedthrough, i.e., the Integrator block.
If you remove the Integrator block from the atomic subsystem, the algebraic loop cannot be eliminated. Hence, attempting to simulate the model results in an error.

![]() | Modeling Dynamic Systems | Modeling and Simulating Discrete Systems | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |