Simulating linear systems with Matlab’s lsim

In this post we will go over a couple of ways to simulate linear systems in Matlab.

You have the transfer-function, say

$$G(s) = \frac{1}{s + 1},$$

and you would like to calculate the response to some input using Matlab. The transfer-function can be represented in Matlab using tf

G = tf([1], [1 1]);

where the two parameters are vectors with the coefficients of the numerator and denominator of the transfer-function.

If your input is bounded and otherwise well behaved you can use lsim to do it. For example, if your input $u$ is a sinusoid of amplitude $A$ and frequency $\omega=2 \pi f$ then

A = 1;
f = 10;
T = 1;
npoints = 10*T*f;
t = linspace(0, T, npoints);
u = A * cos(2*pi*f*t); 

will construct vectors $u$ and $t$ representing your input samples. Note that npoints has to be chosen so that $u$ is well represented by its samples. The output $y$ can be calculated using lsim as in

y = lsim(G, u, t);

Some types of inputs happen so often that matlab will provide specialized functions for simulation. For example, if $u$ is a constant of amplitude $A$ you might as well just use

y = A * step(G);

step by itself calculates the response to a unit step input. See the livescritps for Chapter 4 for more examples of usage of the function step.

Another useful function is impulse, which calculates the unit impulse response. I will comment on that function on a separate note in connection with initial conditions. Indeed, both lsim and step, when used as above, assume zero initial conditions.

You can easily use lsim to simulate the response to multiple inputs as well. For example, you might have calculated closed-loop transfer-functions $H$ and $D$ such that

$$y = H \bar{y} + D w, \qquad H = \frac{G K}{1 + G K}, \qquad D = \frac{G}{1 + G K} $$

using feedback as in

K = 1;
H = feedback(K*G,1);
D = feedback(G,K); 

I will comment on the use of feedback for calculating closed-loop transfer-functions on another post. In this case

yBar = ones(size(t));
w = ones(size(t));
y = lsim([H, D], [yBar; w], t);

will calculate the combined response where yBar and w are vectors with samples of the corresponding inputs. You can also calculate multiple outputs. For example

S = feedback(1,G*K);  
ye = lsim([H; S], yBar, t);

will return an array ye containing both the output signals $e$ and $y$ corresponding to

$$\begin{pmatrix} y \\ e \end{pmatrix} = \begin{bmatrix} H \\ S \end{bmatrix} \bar{y}, \qquad S = \frac{1}{1 + G K}$$

Of course you can do multiple-inputs and multiple-outputs by combining these two ideas.

One thought on “Simulating linear systems with Matlab’s lsim”

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.