Simulink Intro
Simulink is MathWorks' graphical environment for modelling and simulating dynamic systems: things whose state changes over time, such as a car's speed, a motor's current, a tank's water level or a digital controller. Instead of writing equations in code, you draw a block diagram: blocks are operations (integrate, multiply by a gain, add), and the lines between them are signals flowing in time. Simulink then solves the diagram numerically, with the same ODE solvers you met in Integration & ODEs.
Simulink is a separate product that runs inside MATLAB (it needs its own license) and is widely used in automotive, aerospace, robotics and control engineering, often together with automatic C code generation for embedded hardware. GNU Octave has no Simulink and cannot open .slx models. This lesson explains the concepts, and every model is also written as an ordinary MATLAB/Octave simulation that you can run.
Blocks, signals and models
A model is saved as an .slx file (older models: .mdl). You build it by dragging blocks from the Library Browser onto the canvas and connecting their ports:
| Library | Common blocks | Role |
|---|---|---|
| Sources | Step, Constant, Sine Wave, Clock, From Workspace | Produce input signals |
| Sinks | Scope, Display, To Workspace, Outport | Show or record results |
| Math Operations | Gain, Sum, Product, Abs, Saturation | Combine signals |
| Continuous | Integrator, Derivative, Transfer Fcn, State-Space, PID Controller | Continuous-time dynamics |
| Discrete | Unit Delay, Discrete-Time Integrator, Zero-Order Hold | Sampled (digital) systems |
| Signal Routing | Mux, Demux, Switch, Goto/From | Wire signals around |
| User-Defined | MATLAB Function | Your own MATLAB code as a block |
The key idea is the Integrator block: its output is the integral of its input. To model a differential equation, you solve it for the highest derivative, feed that into a chain of integrators, and wire their outputs back into the equation.
Example: a mass on a spring
A mass m hangs on a spring (stiffness k) with a damper (coefficient c), and at t = 0 a constant force F starts pulling it. Newton's second law gives
m x'' = F - c x' - k x so x'' = (F - c x' - k x) / mThe Simulink diagram mirrors the right-hand equation literally:
Step (F) ──►(+)──► Gain 1/m ──► Integrator ──► Integrator ──┬──► Scope
▲ ▲ x'' x' x │
│ └──────── Gain c ◄───┘ │
└────────── Gain k ◄───────────────────────────┘
(both feedback inputs of the Sum block have a minus sign)The first integrator turns acceleration x'' into velocity x', the second turns velocity into position x. The two feedback gains feed c x' and k x back to the Sum block with negative signs. The initial conditions (here 0 and 0) are parameters of the two Integrator blocks, and the Scope plots x over time.
The same model in MATLAB code
Write the state as s = [x; x'], and the diagram becomes a first-order system for ode45, which is also Simulink's default solver for continuous models:
m = 1; c = 0.8; k = 4; F = 2; % block parameters
rhs = @(t, s) [s(2); (F - c * s(2) - k * s(1)) / m];
opts = odeset('RelTol', 1e-8, 'AbsTol', 1e-10);
[t, s] = ode45(rhs, 0:1:10, [0; 0], opts); % Stop time 10, initial conditions 0
fprintf('t = %4.1f s: x = %.4f m\n', [t'; s(:, 1)']);
fprintf('steady state F/k = %.4f m\n', F / k);t = 0.0 s: x = 0.0000 m
t = 1.0 s: x = 0.5637 m
t = 2.0 s: x = 0.6923 m
t = 3.0 s: x = 0.3736 m
t = 4.0 s: x = 0.4778 m
t = 5.0 s: x = 0.5680 m
t = 6.0 s: x = 0.4754 m
t = 7.0 s: x = 0.4819 m
t = 8.0 s: x = 0.5202 m
t = 9.0 s: x = 0.4978 m
t = 10.0 s: x = 0.4920 m
steady state F/k = 0.5000 m
The position overshoots, oscillates and settles towards F/k, the stretch at which the spring force balances the pull. This is what the Scope block would show:
[tp, sp] = ode45(rhs, [0 10], [0; 0], opts); % let the solver choose the time points
plot(tp, sp(:, 1)), hold on
plot([0 10], [F/k F/k], '--', 'Color', [0.5 0.5 0.5]) % steady state
xlabel('Time (s)'), ylabel('x (m)'), title('Scope: x')Solver settings
Every model has Configuration Parameters (Ctrl+E in the model window). The most important ones are on the Solver pane:
| Setting | Meaning | Typical choice |
|---|---|---|
| Start / Stop time | Simulated time span | 0 to 10 (the default stop time) |
| Solver type | Variable-step adapts the step to the dynamics; fixed-step uses a constant step | Variable-step for desktop simulation; fixed-step for code that runs on hardware |
| Solver | auto, ode45, ode23, ode15s/ode23t (stiff), ode4/ode1 (fixed-step RK4/Euler), discrete |
auto picks ode45 for non-stiff continuous models |
| Relative / absolute tolerance | Accuracy target of variable-step solvers | 1e-3 relative (default); tighten if results look jagged |
| Max step size / fixed step size | Upper bound or constant step | auto, or something smaller than the fastest dynamics |
| Zero-crossing detection | Locates events (switches, collisions) precisely | On |
Fixed-step solvers make the step size your responsibility. Here is what Simulink's ode1 (forward Euler) does to the spring model with two step sizes, compared with the accurate ode45 value at t = 10 s (0.4920):
m = 1; c = 0.8; k = 4; F = 2;
for h = [0.1 0.01]
x = 0; v = 0;
for n = 1:round(10 / h)
a = (F - c * v - k * x) / m; % Gain 1/m output
x = x + h * v; % Integrator (Euler step)
v = v + h * a; % Integrator (Euler step)
end
fprintf('ode1, step %-5g: x(10) = %.4f\n', h, x);
endode1, step 0.1 : x(10) = 0.4690
ode1, step 0.01 : x(10) = 0.4909
A step of 0.1 s is visibly wrong; ten times smaller is close. Higher-order fixed-step solvers such as ode4 get much better accuracy for the same step.
Discrete systems: a digital controller
Controllers implemented on a microcontroller run at a fixed sample time. In Simulink you build them from Discrete blocks (Unit Delay, Discrete-Time Integrator, Saturation) or drop in a Discrete PID Controller block. Below, a PI controller with sample time 0.5 s sets the engine force of a 1000 kg car to reach 25 m/s against air drag, with the force limited to 4000 N. While the force is saturated, the integrator is frozen ("anti-windup", an option of the PID block):
Ts = 0.5; mass = 1000; drag = 50; target = 25; % s, kg, N per m/s, m/s
Kp = 400; Ki = 40;
v = 0; integ = 0;
for n = 0:80
t = n * Ts;
err = target - v;
u = Kp * err + Ki * integ; % PI law
if u > 4000
u = 4000; % Saturation block
else
integ = integ + err * Ts; % Discrete-Time Integrator
end
if mod(t, 5) == 0
fprintf('t = %4.1f s v = %5.2f m/s force = %6.1f N\n', t, v, u);
end
v = v + Ts * (u - drag * v) / mass; % plant, sampled
endt = 0.0 s v = 0.00 m/s force = 4000.0 N
t = 5.0 s v = 17.63 m/s force = 3120.6 N
t = 10.0 s v = 23.46 m/s force = 1584.5 N
t = 15.0 s v = 24.57 m/s force = 1317.9 N
t = 20.0 s v = 24.84 m/s force = 1267.8 N
t = 25.0 s v = 24.93 m/s force = 1256.4 N
t = 30.0 s v = 24.96 m/s force = 1252.9 N
t = 35.0 s v = 24.98 m/s force = 1251.5 N
t = 40.0 s v = 24.99 m/s force = 1250.8 N
The force settles at 1250 N, exactly the drag at 25 m/s (50 x 25). In Simulink the car itself would usually stay a continuous model, and the controller blocks would run at Ts; Simulink handles the mixed timing for you.
Driving Simulink from MATLAB code
Everything you can click in Simulink can also be scripted, which is how parameter studies and automated tests are done:
open_system('spring_model') % open the .slx model
set_param('spring_model/Damper', 'Gain', '0.8') % change a block parameter
out = sim('spring_model', 'StopTime', '20'); % run; returns Simulink.SimulationOutput
x = out.logsout.get('x').Values; % a logged signal (timeseries)
plot(x.Time, x.Data)
% sweep a parameter, one SimulationInput per run (parsim runs them in parallel)
for i = 3:-1:1
in(i) = Simulink.SimulationInput('spring_model');
in(i) = in(i).setVariable('c', 0.4 * i);
end
outs = sim(in);Blocks can read MATLAB workspace variables: if a Gain block's parameter is the text c, Simulink looks up c when the simulation starts. Models can even be built entirely by code with new_system, add_block and add_line.
The wider Simulink family
| Product | Adds |
|---|---|
| Stateflow | State machines and flow charts inside models (modes, logic, sequencing) |
| Simscape (+ Electrical, Multibody, Fluids...) | Physical modelling with real components (resistors, joints, pipes) instead of equations |
| Simulink Control Design | Linearise models, tune PID gains automatically |
| Simulink Coder / Embedded Coder | Generate C/C++ code from a model for real-time hardware |
| Simulink Test, Design Verifier | Test harnesses, requirements coverage, formal checks |
Free alternatives for block-diagram simulation include Xcos (part of Scilab) and tools based on the open Modelica language such as OpenModelica. With Octave or plain MATLAB, the approach in this lesson works everywhere: write the diagram's equations as a function and integrate them with ode45 or a fixed-step loop.
Learn more: Integration & ODEs, Systems of ODEs, Toolboxes.
Test yourself
What does an Integrator block output?
- The derivative of its input
- The integral of its input over time
- Its input multiplied by a constant
- The input delayed by one sample
Which solver does Simulink's 'auto' setting typically choose for a non-stiff continuous model?
- ode1
- ode15s
- ode45
- discrete
Why did the Euler simulation with step 0.1 s give a noticeably different x(10)?
- Euler's method is exact only for small masses
- Fixed-step Euler has a large error when the step is not small compared with the dynamics
- The spring constant changed
- ode45 is wrong