Block Diagrams for Simulation

In Chapter 5 we discuss how to produce block diagrams for the simulation of linear and certain nonlinear systems described by ordinary differential equations.

A graphical representation of such diagrams can be directly used in MATLAB Simulink’s for exploring the response of linear and nonlinear systems, as discussed in the following short video:

Simulink also provides higher level blocks, such as transfer-functions of arbitrary order, state-space blocks, etc.

Alternatively, if one does not want to be interacting with a graphical interface, one can use one of the available ODE solvers. In Matlab a popular choice is ode45, which is an implementation of a Runge-Kutta integration method with adaptive step size. Start by writing your system in state-space form


and implement a function that takes in $t$ and $x$ as arguments and produces $\dot{x}$ as output. For example, the function

function xdot = myfun(t, x)
% [x1'; x2'] = [0 1; -1 0] [x1; x2]
xdot = [0 1; -1 0] * x

can be used to simulate the linear system with state-space model

$$\begin{pmatrix} \dot{x}_1 \\ \dot{x}_2 \end{pmatrix}=\begin{bmatrix}0&1\\-1&0\end{bmatrix}\begin{pmatrix}x_1\\x_2\end{pmatrix}$$

Note that the ODE function can be time-varying, that is it depends not only on $x$ but also on $t$. A typical call to ode45 is as in:

tspan=[0 10];
x0 = [1; 0];
[t, x] = ode45(myfun, tspan, x0);

in which the vector tspan contains the initial and final simulation times, and x0 the initial conditions. Upon termination, the vector x contains a number of samples of the state vector $x$ stacked up corresponding to the time values in the vector t. The entire system evolution can be plotted using

plot(t, x);

It used to be a pain to pass parameters to the ODE function but it is now relatively easy to do it using anonymous functions. For example, one could add parameters to the ode function

function xdot = myfun(t, x, A)
% x' = A x
xdot = A * x

and call ode45 as in

A = [0 1; -1 0];
[t, x] = ode45(@(t,x) myfun(t,x,A), tspan, x0);

or simply

[t, x] = ode45(@(t,x) A*x, tspan, x0);

Of course there is little reason to use ode45 if you are simulating a linear system, since you could have used the much more flexible lsim. So we close with a simple nonlinear example

$$\begin{pmatrix} \dot{x}_1 \\ \dot{x}_2 \end{pmatrix}=\begin{pmatrix}x_1-x_1 x_2 \\ .9 x_1 x_2-x_2\end{pmatrix}$$

that could be simulated using

x0 = [1; 1];
[t, x] = ode45(@(t,x) [x(1)-x(1)*x(2);.9*x(1)*x(2)-x(2)], tspan, x0);

ODE solvers such as ode45 are great for simulating the response to initial conditions of systems but not so great if one would have varying input signals. Still waiting for a simple solution in that case…

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.