S-Function
在模型中包含 S-Function
库:
Simulink /
User-Defined Functions
描述
S-Function 模块允许您将用 C、C++ 或 Fortran® 编写的 S-Function 或系统函数算法(称为 C MEX S-Function)集成到 Simulink 模型中。您可以使用该模块来实现 1 级或 2 级 C MEX S-Function。要将您的 S-Function 合并到一个模型中,请在编译 C MEX S-Function 后执行以下操作:
将 S-function 模块从 Simulink 库浏览器拖到您的模型中。
打开模块参数对话框,在 S-Function 名称字段指定 S-Function 名称,以便为 S-function 模块提供功能。例如,键入
timestwo
并选择应用。
S-Function 是以 MATLAB®、C、C++ 或 Fortran 语言编写的 Simulink® 模块的计算机语言描述。如果您有 C、C++ 或 Fortran S-Function,则需要使用 mex
实用工具将它们编译为 MEX 文件(请参阅编译 C MEX 函数)。S-Function 定义模块在仿真的不同部分(例如初始化、更新、求导、输出和终止)如何工作。S-Function 使用一种称为 S-Function API 的特殊调用语法,使您能够与 Simulink 引擎进行交互。这种交互与该引擎和内置 Simulink 模块之间发生的交互非常相似。在仿真的每一步,仿真引擎都会调用一个方法来完成特定任务。
例如,下面是名为 timestwo.c
的简单 C MEX S-Function 的示例,其输出是其输入的两倍。
#define S_FUNCTION_NAME timestwo /* Specifies the name of the S-function (timestwo) */
#define S_FUNCTION_LEVEL 2 /* Specifies that the S-function is in the Level 2 format */
#include "simstruc.h" /* Defines the data structure */
static void mdlInitializeSizes(SimStruct *S) /* Initialize the input and output ports and their size */
{
ssSetNumSFcnParams(S, 0);
if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
return; /* Parameter mismatch reported by the Simulink engine*/
}
if (!ssSetNumInputPorts(S, 1)) return;
ssSetInputPortWidth(S, 0, DYNAMICALLY_SIZED);
ssSetInputPortDirectFeedThrough(S, 0, 1);
if (!ssSetNumOutputPorts(S,1)) return;
ssSetOutputPortWidth(S, 0, DYNAMICALLY_SIZED);
ssSetNumSampleTimes(S, 1);
/* Take care when specifying exception free code - see sfuntmpl.doc */
ssSetOptions(S, SS_OPTION_EXCEPTION_FREE_CODE);
}
static void mdlInitializeSampleTimes(SimStruct *S) /* Set the sample time of the S-function as inherited */
{
ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
ssSetOffsetTime(S, 0, 0.0);
}
static void mdlOutputs(SimStruct *S, int_T tid) /* Calculate the block output for each time step */
{
int_T i;
InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S,0);
real_T *y = ssGetOutputPortRealSignal(S,0);
int_T width = ssGetOutputPortWidth(S,0);
for (i=0; i<width; i++) {
*y++ = 5.0 *(*uPtrs[i]);
}
}
static void mdlTerminate(SimStruct *S){} /* Perform tasks at the end of the simulation */
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */
#include "simulink.c" /* MEX-file interface mechanism */
#else
#include "cg_sfun.h" /* Code generation registration function */
#endif
S-Function 遵循一般形式,可以适应连续、离散和混合系统。您可以在 S-Function 中实现算法,并使用 S-Function 模块将其添加到 Simulink 模型。在编写 S-Function 并将其名称放入 S-Function 模块(在 User-Defined Functions 模块库中提供)后,您可以使用封装来自定义用户界面。在此示例中,使用 mex timestwo.c
编译 timestwo.c
函数,并使用 S-Function 模块实现它。
S-Function 模块显示指定的 S-Function 的名称,以及该 S-Function 指定的输入和输出端口的数量。连接输入端口的信号必须具有 S-Function 为输入端口指定的维度。
注意
使用 Level-2 MATLAB S-Function 模块,在模块图中包含一个 2 级 MATLAB S-Function。
示例
端口
输入
输出
参数
模块特性
扩展功能
版本历史记录
在 R2006a 之前推出