本文主要参考Matlab help 文档。
一个 Level-1 MATLAB S-函数 如下所示:
[sys,x0,str,ts]=f(t,x,u,flag,p1,p2,...)
[
s
y
s
,
x
0
,
s
t
r
,
t
s
]
=
f
(
t
,
x
,
u
,
f
l
a
g
,
p
1
,
p
2
,
.
.
.
)
, 这里
f
f
是S函数名称。
在仿真时,Simulink重复调用 ,使用
flag
f
l
a
g
参数来表明 要为某个特定的调用 将要执行的任务。 S函数执行任务并将结果返回到输出向量中。
下面是 Level-1 MATLAB S-函数的参数:
参数名称 | 含义 |
---|---|
t | Current time |
x | State vector |
u | Input vector |
flag | Integer value that indicates the task to be performed by the S-function |
The following table describes the values that flag can assume and lists the corresponding Level-2 MATLAB S-function method for each value.
Flag Argument
Level-1 Flag | Level-2 Callback Method | Description |
---|---|---|
0 | setup | Defines basic S-Function block characteristics, including sample times, initial conditions of continuous and discrete states, and the sizes array (see Define S-Function Block Characteristics for a description of the sizes array). |
1 | mdlDerivatives | Calculates the derivatives of the continuous state variables. |
2 | mdlUpdate | Updates discrete states, sample times, and major time step requirements. |
3 | mdlOutputs | Calculates the outputs of the S-function. |
4 | mdlOutputs | method updates the run-time objectNextTimeHit property Calculates the time of the next hit in absolute time. This routine is used only when you specify a variable discrete-time sample time in the setup method. |
9 | mdlTerminate | Performs any necessary end-of-simulation tasks. |
相应的代码如下所示: (在文件 sfuntmpl.m 中可以找到)
function [sys,x0,str,ts,simStateCompliance] = sfuntmpl(t,x,u,flag)
switch flag,
% Initialization %
case 0,
[sys,x0,str,ts,simStateCompliance]=mdlInitializeSizes;
% Derivatives %
case 1,
sys=mdlDerivatives(t,x,u);
% Update %
case 2,
sys=mdlUpdate(t,x,u);
% Outputs %
case 3,
sys=mdlOutputs(t,x,u);
% GetTimeOfNextVarHit %
case 4,
sys=mdlGetTimeOfNextVarHit(t,x,u);
% Terminate %
case 9,
sys=mdlTerminate(t,x,u);
% Unexpected flags %
otherwise
DAStudio.error('Simulink:blocks:unhandledFlag', num2str(flag));
end