Design and application of Simulink system simulation example and S function of MATLAB

1. Simulink system simulation example

  • In the following application examples, we will use different modeling methods to model and simulate the system.
  • For example, there is a second-order differential equation x ′ ′ + 0.2 x ′ + 0.4 x = 0.2 u ( t ) x''+0.2x'+0.4x=0.2u(t) with an initial state of 0x′′+0.2x _+0.4x _=0.2 u ( t ) , whereu ( t ) u(t)u ( t ) is a unit step function, for which we try to build a system model and simulate it.

1. Method 1

  • We use the Integrator (integrator) module to directly construct the model to solve the differential equation.
  • We rewrite the original differential equation as x ′ ′ = 0.2 u ( t ) − 0.2 x ′ − 0.4 x x''=0.2u(t)-0.2x'-0.4xx′′=0.2 u ( t )0.2x _0.4x _
  • x ′ ′ x'' x'' After integration, we getx ' x'x x ′ x' x' After the function of the integral module, we can getxxx , whilex ′ x'x' andxxx produces x ′ ′ x''through algebraic operationx’’ , based on which the system model can be established and simulated. Proceed as follows.
  • (1) It is not difficult to establish the system model as shown in the figure below by using the basic modules in the Simulink block library.

insert image description here

  • Each module in the model is described as follows.
  • ① u(t) input module: its Step time is set to 0, and the module name is changed from the original Step to u(t).
  • ② Gs gain module: Gain parameter Gain is set to 0.2.
  • ③ Add summation module: its icon shape is set to rectangular, and the symbol list List of signs is set to ±-.
  • ④ Integrator integration module: The parameters do not need to be changed.
  • ⑤ G1 and G2 feedback gain modules: the gain parameters are set to 0.4 and 0.2 respectively, and their directions can be flipped with the help of Rotate & Flip in the shortcut menu ⟶ \longrightarrow Flip Block command or Diagram of the model editing window⟶ \longrightarrowRotate & Flip ⟶ \longrightarrow Flip Block command implementation.
  • (2) Set the system simulation parameters. Open the Configuration Parameters window and set the simulation termination time to 20s.
  • (3) Simulation operation. Double-click the oscilloscope icon to open the oscilloscope window. Click the Run button in the tool bar of the model editing window, and you can see the change curve of the simulation result in the oscilloscope window, as shown in the figure below.

insert image description here

2. Method 2

  • Modeling with the Transfer Function block (Transfer Fcn).
  • For the equation x ′ ′ + 0.2 x ′ + 0.4 x = 0.2 u ( t ) x''+0.2x'+0.4x=0.2u(t)x′′+0.2x _+0.4x _=Take Laplace transform on both sides of 0.2 u ( t ) , get s 2 X ( s ) + 0.2 s X ( s ) + 0.4 X ( s ) = 0.2 U ( s ) s^{2}X(s)+0.2sX(s )+0.4X(s)=0.2U(s)s2 X(s)+0.2sX(s)+0.4X(s)=0.2U(s)
  • After finishing the transfer function G ( s ) = X ( s ) U ( s ) = 0.2 s 2 + 0.2 s + 0.4 G(s)=\frac{X(s)}{U(s)}=\frac{ 0.2}{s^{2}+0.2s+0.4}G(s)=U(s)X(s)=s2+0.2s+0.40.2
  • There is a standard transfer function (Transfer Fcn) module in the Continuous module library that can be called, so the model for solving the differential equation can be constructed and simulated. According to the system transfer function, the simulation model shown in the figure below is constructed.

insert image description here

  • Each module in the model is described as follows.
  • (1) u(t) module: set the Step time to 0.
  • (2) G(S) module: Double-click the Transfer Fcn module to open the parameter setting dialog box, enter the numerator polynomial coefficient [0.2] in the Numerator coefficients text box, and enter the denominator polynomial coefficient [0.2] in the Denominator coefficients text box Coefficient [1,0.2,0.4], as shown in the figure below.

insert image description here

  • Subsequent operations are the same as method 1.

3. Method 3

  • Modeling with the State Equation Module (State-Space).
  • If let x 1 = x x_{1}=xx1=x x 2 = x ′ x_{2}=x' x2=x , then the differential equationx ′ ′ + 0.2 x ′ + 0.4 x = 0.2 u ( t ) x''+0.2x'+0.4x=0.2u(t)x′′+0.2x _+0.4x _=0.2u(t) 可写成 x ′ = [ x 1 ′ x 2 ′ ] = [ 0 1 − 0.4 − 0.2 ] [ x 1 x 2 ] + [ 0 0.2 ] u ( t ) x'=\begin{bmatrix}x^{'}_{1} \\x^{'}_{2} \end{bmatrix}=\begin{bmatrix} 0&1 \\ -0.4&-0.2 \end{bmatrix}\begin{bmatrix}x_{1} \\x_{2} \end{bmatrix}+\begin{bmatrix}0 \\0.2 \end{bmatrix}u(t) x=[x1x2]=[00.410.2][x1x2]+[00.2]u(t)
  • Write the state equation as { x ′ = A x + B uy = C x + D u \left\{\begin{matrix}x^{'}=Ax+Bu \\y=Cx+Du \end{matrix}\ right.{ x=Ax+B uy=Cx+From _
  • Similarly, A = [ 0 1 − 0.4 − 0.2 ] A=\begin{bmatrix} 0&1 \\ -0.4 &-0.2 \end{bmatrix}A=[00.410.2] B = [ 0 − 0.2 ] B=\begin{bmatrix} 0 \\ -0.2 \end{bmatrix} B=[00.2] C = [ 1 0 ] C=\begin{bmatrix} 1&0 \end{bmatrix} C=[10] D = 0 D=0 D=0
  • There is a standard state equation (State-Space) module in the Continuous module library that can be called, so the model for solving the differential equation can be constructed and simulated. According to the system state equation, the simulation model shown in the figure below is constructed.

insert image description here

  • Each module in the model is described as follows:
  • (1) u(t) input module: its Step time is set to 0.
  • (2) State-Space module: Enter [0,1;-0.4,-0.2], [0;0.2], [1,0] and 0 in each text box of A, B, C, and D in sequence, as shown in the figure below Show.

insert image description here

  • Subsequent operations are the same as method 1.

2. Design and application of S function

  • The S-function is used to develop new Simulink general-purpose function blocks, and is a tool for extending the block library. S-functions can be written in MATLAB language, C, C++, FORTRAN and other languages.
  • Using text to input formulas and equations in the S function is very suitable for the mathematical description of complex dynamic systems, and can control the simulation more precisely during the simulation process.
  • The S function is called a system function (System Function), which describes the function module in a non-graphical way.
  • The S function written in MATLAB language can make full use of the rich resources provided by MATLAB, and conveniently call various toolbox functions and graphics functions for use;
  • The S function written in C language can realize the visit to the operating system, such as realizing communication and synchronization with other processes.
  • S-functions written in languages ​​other than MATLAB need to use a compiler to generate MEX-files.

1. Write the S-function in MATLAB language

  • S-function has a fixed program format, and you can build your own S-function from the S-function template program provided by Simulink.

1.1 Main program

  • The leading statement of the main program of the S function is as follows:
function [sys,x0,str,ts]=fname(t,x,u,flag)
  • Among them, fname is the function name of S function, t, x, u, flag are respectively simulation time, state vector, input vector and subroutine call flag. flag controls which subroutine of the S function is called at each stage of the simulation, and its meaning and related information are shown in the table below.
value Function call function name return parameter
0 initialization mdllnitializeSizes sys is the initialization parameter, x0, str, ts are as defined
1 Compute the derivative of a continuous state variable mdlDerivatives sys returns continuous status
2 Computing Updates for Discrete State Variables mdIUpdate sys returns discrete state
3 Calculate the output signal mdlOutputs sys returns system output
4 Compute the next sampling instant mdlGetTimeOfNextVarHit sys returns the time of the next simulation
9 end simulation task mdlTerminate none
  • These 4 parameters must be given each time Simulink calls the S function. sys, x0, str, and ts are the return parameters of the S function.
  • sys is a general symbol that returns parameters, and what kind of parameters it gets depends on the flag value. For example, when flag=3, what sys gets is the output vector value of S function.
  • x0 is the initial state value, if there is no state variable in the system, x0 will get an empty array.
  • str is only used for consistency verification between the system model and the S-function API (application programming interface). For M-file S-functions, it will be set as an empty array.
  • ts is a two-column matrix, one column is the sampling period of each state variable in the S-function, and the other column is the offset of the corresponding sampling time. The sampling periods are in increasing order, with a row in ts corresponding to a sampling period. For continuous systems, both the sampling period and the offset should be set to 0. If the sampling period is taken as -1, the sampling period of the input signal will be inherited.
  • In addition, the input parameters of the main program can also include user-defined parameter lists: pl, p2, ..., pn, which are optional variables that you want to assign to the S function, and their values ​​are set through the parameter dialog box of the corresponding S function. You can also assign values ​​in the command line window.
  • So the leading statement of the main program of the S function can be written as
function [sys,x0,str,ts]=fname(t,x,u,flag,pl,p2,,pn)
  • The main program uses a switch-case statement to guide Simulink to the correct subroutine.

1.2 Subroutines

  • There are 6 subroutines in the M file S function, which are called by Simulink at different stages of simulation, and the prefix of these subroutines is mdl.
  • Every time the S function is called, a flag value must be given, and the subroutine corresponding to the flag value in the S function is actually executed.
  • At different stages of simulation, Simulink needs to call different subroutines in the S function.
  • (1) Initialize the subroutine mdlInitializeSizes. Subroutine mdlInitializeSizes defines S function parameters, such as sampling time, input volume, output volume, number of state variables, and other characteristics.
  • In order to provide this information to Simulink, at the beginning of the subroutine mdlInitializeSizes, the simsizes function should be called. This function returns a sizes structure. The members of the structure sizes.NumContStates, sizes.NumDiscStates, sizes.NumOutputs and sizes.NumInputs represent continuous state variables respectively The number of discrete state variables, the number of outputs, and the number of inputs. These 4 values ​​can be set to -1 to change their size dynamically.
  • The member sizes.DirFeedthrough is a direct flag, that is, whether the input signal appears directly at the output terminal. Whether it is set to direct depends on whether the output is a function of the input, or whether the sampling time is a function of the input. 1 means yes, 0 means no. Member sizes.NumSampleTimes is the number of sampling periods of the module, usually 1.
  • The size of the structure set according to the requirements is assigned to the sys parameter with the statement sys=simsizes(sizes). In addition to sys, the system's initial state variable x0, description variable str and sampling period variable ts should also be set.
  • (2) Other subroutines. The dynamic update of the state uses two subroutines, mdlDerivatives and mdIUpdate, the former is used for the update of the continuous state, and the latter is used for the update of the discrete state. The output values ​​of these functions, the corresponding states, are returned by sys variables.
  • For a hybrid system containing both continuous and discrete states, it is necessary to write these two functions at the same time to describe the continuous and discrete states respectively.
  • The calculation of the module output signal uses the mdlOutputs subroutine, and the output of the system is still returned by the sys variable.
  • In general applications, the flags 4 and 9 are rarely used, and the two subroutines mdlGetTimeOfNextVarHit and mdlTerminate are rarely used.

2. Application of S function

  • Let's look at two simple examples of M-file S-functions.
  • For example, we use the S function to realize y = nxy=nxy=n x , that is, to amplify an input signal bynnn times.
  • (1) Use MATLAB language to write the S function, the program is as follows.
%****************************************
%S函数timesn.m,其输出是输入的n倍
%****************************************
function [sys,x0,str,ts]=timesn(t,x,u,flag,n)
switch flag
    case 0
        [sys,x0,str,ts]=mdlInitializeSizes;         %初始化
    case 3
        sys=mdloutputs(t,x,u,n);                    %计算输出量
    case {
    
    1,2,4,9}
        sys=[];
    otherwise                                       %出错处理
        error(num2str(flag));
end
%****************************************
%mdlInitializesizes:当flag为0时进行整个系统的初始化
%******************** ********************
function [sys,x0,str,ts]=mdlInitializeSizes()       
%调用函数simsizes以创建结构sizes
sizes=simsizes;
%用初始化信息填充结构sizes
sizes.NumContStates=0;          %无连续状态
sizes.NumDiscStates=0;          %无离散状态
sizes.NumOutputs=1;             %有一个输出量
sizes.NumInputs=1;              %有一个输入信号
sizes.DirFeedthrough=1;         %输出量中含有输入量
sizes.NumSampleTimes=1;         %单个采样周期
%根据上面的设置设定系统初始化参数
sys=simsizes(sizes);
%给其他返回参数赋值
x0=[];                          %设置初始状态为零状态
str=[];                         %将str变量设置为空字符串
ts=[-1,0];                      %假定继承输入信号的采样周期
%初始化子程序结束
%****************************************
% mdlOutputs:当flag值为3时,计算输出量
%****************************************
function sys=mdloutputs(t,x,u,n)
sys=n*u;
%输出量计算子程序结束
  • Save the program with the file name timesn.m. After compiling the S function, the module can be packaged and tested.
  • (2) Module packaging and testing.
  • ① Establish the connection between the S-function module and the written S-function file. Create a new model, add the S-Function module, Sine Wave module and Scope module in the User-Defined Functions submodule library to the model editing window, and build the simulation model as shown in the figure below.

insert image description here

  • Double-click the S-function module in the model editing window to open the parameter dialog box as shown in the figure below, enter the S function name timesn in the S-function name edit box, and enter the external parameter n in the S-function parameters edit box.
  • n can be defined with commands in the MATLAB workspace. If there are multiple external parameters, separate them with commas.

insert image description here

  • ② Model encapsulation. Its specific operation is similar to the encapsulation of subsystems. Select the S-Function module in the model editing window, and then select Diagram ⟶ \longrightarrowMask ⟶ \longrightarrow ⟶Create Mask command, or press Ctrl+M keys, open the package editor, select the Parameters & Dialog tab, click the Edit tool in the control toolbox on the left, and add an edit box control to the control list in the Dialog box area in the middle #1. After selecting the control, in the Property editor area on the right, enter n in the Name column, enter "magnification" in the Prompt column, and check the Evaluate check box, as shown in the figure below.

insert image description here- Click the OK button after setting is complete. After the S-function module is encapsulated, double-click it to get the module parameter dialog box as shown in the figure below.

insert image description here

  • When the value of input n is 10, the obtained simulation result is shown in the figure below.

insert image description here

  • For example, we use the S-function to construct a nonlinear piecewise function y = { 3 xx < 1 3 1 ≤ x < 3 3 − ( x − 3 ) 2 3 ≤ x < 4 2 4 ≤ x < 5 2 − ( x − 5 ) 2 5 ≤ x < 6 1 x ≥ 6 y=\left\{\begin{matrix} 3\sqrt{x}& x< 1\\ 3 & 1\le x< 3\\ 3-(x-3 )^{2} &3\le x< 4 \\ 2 & 4\le x< 5\\ 2-(x-5)^{2} & 5\le x< 6\\ 1 &x\ge 6 \end {matrix}\right.y= 3x 33(x3)222(x5)21x<11x<33x<44x<55x<6x6
  • (1) Use the MTALAB language to write the S function, the program is as follows:
function [sys,x0,str,ts]=sfunction(t,x, u,flag)
switch flag
    case 0
        [sys,x0,str,ts]=mdlInitializeSizes;
    case 3
        sys=mdlOutputs(t,x,u);
    case {
    
    1,2,4,9}
        sys=[];
    otherwise
        error(['Unhandled flag=',num2str(flag)]);
end
function [sys,x0,str,ts]=mdlInitializeSizes
sizes=simsizes;
sizes.NumContStates=0;
sizes.NumDiscStates=0;
sizes.NumOutputs=1;
sizes.NumInputs=1;
sizes.DirFeedthrough=1;
sizes.NumSampleTimes=1;
sys=simsizes(sizes);
x0=[];
str=[];
ts=[0,0];
function sys=mdlOutputs(t,x,u)
if u<1
    sys=3*sqrt(u);
elseif u>=1&&u<3
    sys=3;
elseif u>=3&&u<4
    sys=3-(u-3)^2;
elseif u>=4&&u<5
    sys=2;
elseif u>=5&&u<6
    sys=2-(u-5)^2;
else
    sys=1;
end
  • Save the program with the filename sfunction.m.
  • (2) Module testing. Add the S-Function module to the model editing window, and enter the M file name sfunction in its parameter setting dialog box to build the simulation model as shown in the figure below.

insert image description here

  • Run it to get the simulation result as shown in the figure below.

insert image description here

Guess you like

Origin blog.csdn.net/weixin_45891612/article/details/131501611