Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 36 ยท Projects and Practice

Practice: Simulink Troubleshooting, Debugging and Design Review

Practice fixing common Simulink problems: algebraic loops, solver and step-size trouble, sample time errors, unexpected Stateflow behavior, slow models, plus a review checklist and exercises.

Every Simulink user meets the same handful of problems: an algebraic loop warning, a simulation that crawls, results that change with the step size, a Stateflow chart that "does the wrong thing". This final lesson collects them: how to recognize each problem, the tools that show its cause, and the fix. It ends with a design review checklist and exercises with solutions. Simulink does not run on this site, so we describe messages and menus, and the Python stand-ins illustrate causes (a loop detector, a step-size experiment) without reproducing Simulink's output.

A debugging mindset

  1. Reproduce with the smallest model; use a harness to isolate the component.
  2. Look at the signals: log them, then inspect them in the Simulation Data Inspector (SDI).
  3. Read the Diagnostic Viewer: click the block name in the message; it highlights the block in the model.
  4. Change one thing at a time (solver, step size, parameter) and compare runs in SDI.
  5. Fix the cause, not the symptom: widening a tolerance or adding a delay is a design change, not a fix.

Tools you should know

Tool Use
Diagnostic Viewer Errors and warnings with links to blocks
Simulation Data Inspector Plot, compare and diff logged signals between runs
Simulink Debugger (Debug tab > Step) Step through blocks in execution order, set breakpoints, see block I/O
Sorted order display (Debug > Information Overlays > Execution Order) Shows the order blocks execute in
Sample Time Display (Information Overlays > Colors / Sample Time Legend) Colors blocks by rate, finds rate mismatches
Signal logging and Data Display Log selected signals, show values on lines
Model Advisor Static checks (Model Advisor lesson)
Profiler (Analysis > Performance Tools > Simulink Profiler) Shows where simulation time is spent
Performance Advisor Suggests settings to speed up simulation
Stateflow debugger Breakpoints and animation inside charts
Solver Profiler Shows step-size changes and zero-crossings with variable-step solvers

Problem 1: algebraic loops

An algebraic loop occurs when a signal feeds back to its own input through blocks that have direct feedthrough (output depends on the current input, with no delay or integration). Simulink must solve an equation at every step, which is slow and may fail, and code generation may not support it. Message: "Algebraic loop detected".

Fixes: break the loop with a Unit Delay or Memory block, move the feedback through an integrator or a block without direct feedthrough, or restructure the equations. If the loop is intentional, it should be minimized and bounded with an Algebraic Constraint block; set Diagnostics > Algebraic loop to error so you notice new ones.

The stand-in finds loops in a block graph, the same idea as Simulink's sorting step: a cycle through direct-feedthrough blocks only.

Python Stand-in: detect an algebraic loop in a block diagram

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Problem 2: results depend on the solver or step size

A simulation that changes drastically when you change the step size is a sign that the step is too large for the dynamics or that the system is stiff (fast and slow parts together).

  • Variable-step solvers (ode45, ode23, ode15s for stiff, ode23t): the solver chooses the step within Relative tolerance (default 1e-3) and Absolute tolerance (auto). Tighten the tolerance, or limit Max step size so that events such as a pulse train are not skipped.
  • Fixed-step solvers (ode1 Euler, ode3, ode4 Runge-Kutta): you choose the step. Required for code generation. Use a step at most one tenth of the fastest time constant.
  • A "Stiff" symptom: the step size collapses to tiny values and the simulation slows to a crawl; switch to ode15s or ode23t.
  • Zero-crossing detection (relays, switches, saturation) can cause many steps in a variable-step solver; reduce Zero-crossing control or use Zero-Crossing options on blocks that jitter around a threshold.

The stand-in shows a stable and an unstable Euler run on a fast decaying system to illustrate why the fixed step matters.

Python Stand-in: Euler step size versus stability

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Forward Euler is stable here only if dt < 2/50 = 0.04. The run at 0.05 explodes, which is what a too-large fixed step looks like.

Problem 3: sample time problems

Messages such as "Sample time mismatch" or "Sample time of ... must be a multiple of the fundamental sample time". Causes: blocks with different explicit sample times connected directly, a continuous block feeding a discrete one in a model meant to be fully discrete, or sample times that are not integer multiples. Fixes: choose a base rate (for example 1 ms) and use multiples (1e-3, 5e-3, 10e-3), put Rate Transition blocks between rates (set Ensure data integrity and deterministic transfer for code generation), and display the sample times with Debug > Information Overlays > Sample Time Legend.

Problem 4: the initial conditions and the first step

Symptoms: outputs jump at t = 0, or a NaN appears. Check initial conditions of Integrators, Unit Delays and Stateflow data (they default to 0), the Initial output of a Switch or Merge block, uninitialized Data Store Memory, and divisions by zero at the first step. In Model Settings > Diagnostics > Data Validity, set Inf or NaN block output, Division by singular matrix, and Wrap on overflow to error.

Problem 5: Stateflow does not behave as drawn

  • No transition fires: check the data types and values of the condition inputs (print them or show them with the debugger); a condition on a single compared exactly to a double constant may never be true.
  • Wrong transition order: set explicit execution order (transitions lesson).
  • Chart runs at the wrong rate: check the Update method and sample time (first chart lesson).
  • A timeout never ends: after(n, sec) restarts when the state is re-entered by a self-loop; confirm that the state is not being re-entered.
  • Two parallel states disagree: they write the same variable; make one state the only writer and set the execution order.
  • Unreachable states: use the Stateflow debugger and the coverage report to find them (coverage lesson).

Problem 6: the model is slow

Use the Profiler and Performance Advisor. Common causes: Scopes and logging of every signal at a tiny sample time (limit points to log, decimate), MATLAB Function blocks run in the interpreter (turn on Accelerator mode, or generate code with Rapid Accelerator), variable-step solvers with too many zero-crossings, huge fixed-point models in Normal mode, and ode15s with a bad Jacobian. Use Accelerator for long runs, Fast Restart for repeated runs of the same model with different parameters, and parsim for parallel parameter sweeps.

Problem 7: results differ between simulation and generated code

Use SIL and PIL (deployment lesson): check word sizes in Hardware Implementation, integer division and rounding settings, single versus double blocks, and unspecified (uninitialized) data. Compare in SDI with tolerances.

A design review checklist

  • Requirements: every requirement has an implementation and at least one verification link; each test traces to a requirement.
  • Architecture: plant and controller are separate; interfaces use buses with named fields, units documented in a data dictionary.
  • Timing: one base sample time, explicit rate transitions, no algebraic loops, solver fixed-step for the controller.
  • Data types: explicit; fixed-point ranges collected with margin; saturation on overflow reviewed.
  • Stateflow: default transitions, explicit execution order, else-branches, no deep nesting, timers in seconds.
  • Tests: boundary and fault cases, parameter sweeps, coverage with justifications, back-to-back SIL (and PIL).
  • Standards: Model Advisor configuration passes (or has justified exclusions); naming and layout follow the team guideline.
  • Code: report read, MISRA findings reviewed, execution time and stack measured on the target.

Exercises

Try each one before reading the solution.

  1. A model shows "Algebraic loop detected". The loop runs through a Sum, a Gain and back into the Sum. Why does the loop exist, and how do you break it?
  2. Your variable-step simulation of a pulse train misses some pulses. What setting do you change?
  3. A discrete controller at 1 ms feeds a discrete filter at 10 ms. What block do you add, and which setting guarantees deterministic data transfer?
  4. A Stateflow chart should leave state Heating after 30 s but sometimes leaves after 5 s. What do you suspect?
  5. The same model generates correct results in SIL but wrong results in PIL. What do you check first?
  6. You need a state variable to persist between steps inside a chart, but not be visible as an output. Which data scope?
  7. A saturation limits a signal at 100, but the integrator grows to 5000. What is this and what feature fixes it?
  8. Name two ways to give a chart an input that is a Simulink signal.
Python Stand-in: self-check of your answers (edit the strings and run)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your answers against these. For question 1, the Sum and the Gain both pass their current input to their output, so the signal depends on itself in the same step; a Unit Delay in the feedback path (which changes the design by one sample) or an algebraic rearrangement breaks it. For question 8, input data is the usual way; Data Store Memory is an alternative.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is an algebraic loop?

    Without a delay or state in the loop, the output depends on itself in the same step.
  2. 2. Which solver family is required for code generation to a real-time target?

    A real-time system needs a fixed base rate.
  3. 3. A variable-step simulation slows to a crawl with tiny steps. What is a likely cause and fix?

    Stiff dynamics force explicit solvers to use tiny steps; stiff solvers cope better.
  4. 4. Which tool shows where simulation time is spent?

    The profiler lists the blocks and functions that use the most time.
  5. 5. Why is changing a tolerance to make a failing test pass a bad fix?

    A fix should address the cause; a wider tolerance weakens the test.

Summary

  • Debug systematically: reproduce small, inspect signals in SDI, read the Diagnostic Viewer, change one thing at a time.
  • Algebraic loops, solver and step-size issues, sample time mismatches, initial conditions and Stateflow ordering cover most problems.
  • Use the Profiler, Accelerator and Fast Restart for speed; SIL and PIL for simulation-versus-code differences.
  • Keep a review checklist covering requirements, timing, data types, Stateflow, tests, standards and code.

Next: Back to the Simulink course page