In this tutorial, we explain how to simulate responses of state-space models to arbitrary control inputs in MATLAB. We first explain how to define a state-space model in MATLAB. After that, we define an arbitrary control input, and we simulate the state-space model for the defined control input in MATLAB. The YouTube tutorial accompanying this post is given below.
As a test case, in this tutorial, we consider a second-order mass-spring-damper system whose dynamics is derived by applying Newton’s second law. The dynamics is described by the following ordinary differential equation
(1)
where is the mass, is the damping constant, is the spring constant, is the displacement of the mass, is the first time derivative of , and is the second time derivative of . The force acts as a control input. By assigning the state-space variables
(2)
from (1), we obtain a state space model
(3)
where
(4)
First, we need to define the model parameters and the state-space model. We use the MATLAB code given below to perform these tasks:
clear, clc
m=0.1
ks=5
kd=0.01
A=[0 1;
-ks/m -kd/m];
B=[0; 1/m];
C=[1 0];
D=0
ssModel=ss(A,B,C,D);
To define the state-space model, we use MATLAB’s function ss(). The input arguments of this function are the system matrices. Next, we need to define the input for the simulation:
time=0:0.01:15
controlU=30*sin(2*time)-10*cos(4*time)
figure(1)
plot(time, controlU)
The input is shown in the figure below.
To simulate the state-space model for this input, we use MATLAB’s function lsim():
figure(2)
lsim(ssModel,controlU,time)
The first input argument of lsim() is the defined state-space model. The second input argument is the vector defining the control input as a function of a discrete time, and the final control input is the time vector that is used to define the control input. The generated response is shown in the figure below.
Often, it is necessary to extract the numerical values of the simulated response, we can do that by explicitly specifying the outputs of the lsim() function. The lsim() function will return the simulated output and the time vector used to simulate the output. The code given below will return the time series of the simulated output and it will plot the simulated output in a new figure.
[ys,ti]=lsim(ssModel,controlU,time)
figure(3)
plot(ti,ys)
Finally, in the lsim() function, as the last argument, we can specify the initial condition for the simulation:
X0=[2; -2]
[ys2,ti2]=lsim(ssModel,controlU,time,X0)
figure(4)
plot(ti2,ys2)
The simulated output for the specified initial condition is shown in the figure below.