S函数M文件matlab示范详解教程
- 格式:pdf
- 大小:107.38 KB
- 文档页数:3
S函数的简介及编写摘自恒润科技S-function的编写1. S函数模板编辑环境进入:在MATLAB主界面中直接输入:edit sfuntmpl即可弹出S函数模板编辑的M文件环境,修改即可。
在MATLAB主界面中直接输入:sfundemos,即可调出S 函数的许多编程例子。
2. S函数模板的相关基础:1)M文件S函数的引导语句为:xtflagfuFunction[psysxstrtsp,,12,...),,,0,],(,S函数默认的四个输入参数:t ,x ,u ,flagS函数默认的四个输出函数:sys ,x0 ,str ,ts各个参数的含义如下:T :代表当前的仿真时间,该输入决定了下一个采样时间;X :表示状态向量,行向量,引用格式:X(1),X(2)U :表示输入向量;Flag :控制在每一个仿真阶段调用哪一个子函数的参数,由SIMULINK在调用时自动取值;Sys :通用的返回变量,返回的数值决定Flag值,mdlUpdates里:列向量,引用格式:Sys(1,1),Sys(2,1);mdlOutputs里:行向量,引用格式:Sys =x、X0 :初始的状态值;列向量,引用格式:X0=[ 0;0;0 ]Str :空矩阵,无具体含义;Ts :包含模块采样时间与偏差的矩阵。
[period, offset]当Ts为-1时,表示与输入信号同采样周期。
2)S函数工作方式:Flag = 0时,调用mdlInitializeSizes函数,定义S函数的基本特性,包括采样时间,连续或者离散状态的初始条件与Sizes数组;Flag = 1时,调用mdlDerivatives函数,计算连续状态变量的微分方程;求所给表达式的等号左边状态变量的积分值的过程。
Flag = 2时,调用mdlUpdate函数,用于更新离散状态,采样时间与主时间步的要求;Flag = 3时,调用mdlOutputs函数,计算S函数的输出;Flag = 4时,调用mdlGetTimeOfNextVarHit函数,计算下一个采样点的绝对时间,这个方法仅仅就是使用户在mdlInitializeSize 里说明一个可变的离散采样时间;Flag = 9时,调用mdlTerminate函数,实现仿真任务的结束。
function [sys,x0,str,ts] = sfuntmpl(t,x,u,flag)% SFUNTMPL 是M—文件S函数模板% 通过剪裁,用户可以生成自己的S函数,不过一定要重新命名%利用S函数可以生成连续、离散混合系统等,实现任何模块的功能%%M-文件S函数的语法为:%[SYS,X0,STR,TS]= SFUNC(T,X,U,FLAG,P1,。
,Pn)%% 参数含义:% t是当前时间% x是S函数相应的状态向量% u是模块的输入%flag是所要执行的任务%%FLAG 结果功能% -——-- -——--———-----—--———————--—----—-—--—----—-------—-% 0 [SIZES,X0,STR,TS]模块初始化% 1 DX 计算模块导数% 2 DS 更新模块离散状态% 3 Y 计算模块输出% 4 TNEXT 计算下一个采样时间点% 9 []结束仿真%%% 用户切勿改动输出参数的顺序、名称和数目%输入参数的数目不能小于1,这四个参数的名称和排列顺序不能改动% 用户可以根据自己的要求添加额外的参数,位置依次为第5,6,7,8,9等.% S函数的flag参数是一个标记变量,具有6个不同值,分别为0,1,2,3,4,9 % flag的6个值分别指向6个不同的子函数% flag所指向的子函数也成为回调方法(Callback Methods)switch flag,%初始化,调用“模块初始化"子程序%case 0,[sys,x0,str,ts]=mdlInitializeSizes;%连续状态变量计算,调用“计算模块导数”子函数%case 1,sys=mdlDerivatives(t,x,u);%更新,调用“更新模块离散状态”子函数%case 2,sys=mdlUpdate(t,x,u);%输出,调用“计算模块输出”子函数%case 3,sys=mdlOutputs(t,x,u);%计算下一时刻采样点,调用“计算下一个采样时刻点"子函数%case 4,sys=mdlGetTimeOfNextVarHit(t,x,u);%结束,调用“结束仿真"子函数%case 9,sys=mdlTerminate(t,x,u);%其他的flag%otherwiseDAStudio.error(’Simulink:blocks:unhandledFlag', num2str(flag));end% end sfuntmpl%============================================================= ================%“模块初始化”子函数% 返回大小、初始条件和样本function [sys,x0,str,ts]=mdlInitializeSizes%调用simsizes函数,返回规范格式的sizes构架% 这条指令不要修改sizes = simsizes;% 模块的连续状态个数,0是默认值%用户可以根据自己的要求进行修改sizes.NumContStates = 0;%模块的离散状态个数,0是默认值%用户可以根据自己的要求进行修改sizes.NumDiscStates = 0;% 模块的输出个数,0是默认值% 用户可以根据自己的要求进行修改sizes.NumOutputs = 0;%模块的输入个数,0是默认值% 用户可以根据自己的要求进行修改sizes。
MATLAB S-Function是一种特殊的M文件函数,用于创建自定义的Simulink模块。
它允许用户编写自己的Simulink块,以扩展Simulink的功能和适应特定的应用需求。
在MATLAB中,S-Function通过定义M文件和一组参数来实现。
在使用MATLAB S-Function时,参数起着至关重要的作用。
参数用于在S-Function和Simulink模型之间进行数据传递和通信。
它们可以控制S-Function的行为,影响模型的仿真结果,以及改变模型的外部接口。
了解和熟练使用S-Function参数是使用MATLAB进行模型开发和仿真的重要技能。
接下来,我们将详细介绍MATLAB S-Function参数的使用方法和技巧,帮助用户更好地理解和应用S-Function。
一、S-Function参数的作用S-Function参数是S-Function的输入和输出。
它们可以用于以下几个方面:1. 控制S-Function的行为。
通过设置参数来开启或关闭某些功能,调整模型的参数等。
2. 设置S-Function的输入和输出端口。
参数可以指定输入和输出端口的数量、名称、类型等。
3. 传递数据到S-Function中。
参数可以作为S-Function的输入,传递数据到S-Function中,影响S-Function的行为和输出结果。
4. 从S-Function中获取数据。
参数可以作为S-Function的输出,将S-Function的计算结果返回给Simulink模型其他部分使用。
二、S-Function参数的定义和声明在编写S-Function时,首先需要定义和声明参数。
通常,参数的定义和声明是在S-Function的初始化函数中完成的。
以下是一个简单的示例:```matlabfunction [sys,x0,str] = sfun(t,x,u,flag,param1,param2,param3) switch flagcase 0 Initialization[sys,x0,str] = mdlInitializeSizes(param1,param2,param3);case 3 Outputssys = mdlOutputs(t,x,u,param1,param2,param3);case {1, 2, 4, 9} Unused flagssys = [];otherwiseerror(['Unhandled flag = ',num2str(flag)]); endendfunction [sys,x0,str,ts] = mdlInitializeSizes(param1,param2,param3) Initialize the state xx0 = 0;sys = 0;Return the details of the S-functionsizes = simsizes;sizes.NumContStates = 0;sizes.NumDiscStates = 1;sizes.NumOutputs = 1;sizes.NumInputs = 1;sizes.DirFeedthrough = 1;sizes.NumSampleTimes = 1;sys = simsizes(sizes);str = [];ts = [0 0];endfunction sys = mdlOutputs(t,x,u,param1,param2,param3)Compute the output of the S-functiony = u(1) + param1 * u(1) + param2 * u(1)^2 + param3 * u(1)^3; sys = y;end```在上面的例子中,我们定义了三个参数param1、param2和param3,并在初始化函数和输出函数中使用了这些参数。
matlab中s函数编写心得函数是system Function的简称,用它来写自己的simulink模块。
(够简单吧,^_^,详细的概念介绍大伙看帮助吧)可以用matlab、C、C++、Fortran、Ada等语言来写,这儿我只介绍怎样用matlab语言来写吧(主要是它比较简单)先讲讲为什么要用s函数,我觉得用s函数可以利用matlab的丰富资源,而不仅仅局限于simulink提供的模块,而用c或c++等语言写的s函数还可以实现对硬件端口的操作,还可以操作windows API等的先介绍一下simulink的仿真过程(以便理解s函数),simulink的仿真有两个阶段:一个为初始化,这个阶段主要是设置一些参数,像系统的输入输出个数、状态初值、采样时间等;第二个阶段就是运行阶段,这个阶段里要进行计算输出、更新离散状态、计算连续状态等等,这个阶段需要反复运行,直至结束。
在matlab的workspace里打edit sfuntmpl(这是matlab自己提供的s函数模板),我们看它来具体分析s函数的结构。
它的第一行是这样的:function[sys,x0,str,ts]=sfuntmpl(t,x,u,flag)先讲输入与输出变量的含义:t是采样时间,x是状态变量,u是输入(是做成simulink模块的输入),flag是仿真过程中的状态标志(以它来判断当前是初始化还是运行等);sys 输出根据flag的不同而不同(下面将结合flag来讲sys的含义),x0是状态变量的初始值,str是保留参数(mathworks公司还没想好该怎么用它,嘻嘻,一般在初始化中将它置空就可以了,str=[]),ts是一个1×2的向量,ts(1)是采样周期,ts(2)是偏移量。
下面结合sfuntmpl.m中的代码来讲具体的结构:switch flag,%判断flag,看当前处于哪个状态case0,[sys,x0,str,ts]=mdlInitializeSizes;flag=0表示处于初始化状态,此时用函数mdlInitializeSizes进行初始化,此函数在sfuntmpl.m的149行我们找到他,在初始化状态下,sys是一个结构体,用它来设置模块的一些参数,各个参数详细说明如下size=simsizes;%用于设置模块参数的结构体用simsizes来生成sizes.NumContStates=0;%模块连续状态变量的个数sizes.NumDiscStates=0;%模块离散状态变量的个数sizes.NumOutputs=0;%模块输出变量的个数sizes.NumInputs=0;%模块输入变量的个数sizes.DirFeedthrough=1;%模块是否存在直接贯通(直接贯通我的理解是输入能%直接控制输出)sizes.NumSampleTimes=1;%模块的采样时间个数,至少是一个sys=simsizes(sizes);%设置完后赋给sys输出举个例子,考虑如下模型:dx/dt=fc(t,x,u)也可以用连续状态方程描述:dx/dt=A*x+B*ux(k+1)=fd(t,x,u)也可以用离散状态方程描述:x(k+1)=H*x(k)+G*u(k)y=fo(t,x,u)也可以用输出状态方程描述:y=C*x+D*u设上述模型连续状态变量、离散状态变量、输入变量、输出变量均为1个,我们就只需改上面那一段代码为:(一般连续状态与离散状态不会一块用,我这儿是为了方便说明)sizes.NumContStates=1;sizes.NumDiscStates=1;sizes.NumOutputs=1;sizes.NumInputs=1;其他的可以不变。
1.字符串1.)字符串查找K=findstr(S1,S2)或strfind(S1,S2)例:s='how much wood would a woodchuck chuck?'a=findstr(s,'a')2.)把S1中的S2子字符串都换成S3 , S=strrep(S1,S2,S3)例:S1='This is a beautiful women!'strrep(S1,'women','girl')2.多项式1.)向量转换为多项式,poly2sym()例:P=[3 5 0 1 0 12]y=poly2sym(P)2.)计算多项式的值y=polyval(P,X)%计算以向量P为系数的多项式在X处的值,y=polyvalm(P,X)%计算以向量P为系数的多项式在方阵X的值例:p=[1 -20 -16 480 98]x=4polyval(p,x)3.)求多项式的根例:p=[1 0 3 12 -7]roots(p)4.)多项式的求导和积分,polyder()和polyint()3.数组1.)求点积例:x1=[11 22 33 44]x2=[1 2 3 4]a=dot(x1,x2) %或sum(x1.*x2)2.)求叉积例:x1=[11 22 33]x2=[1 2 3]x3=cross(x1,x2)3.)求混合积例:a=[1 2 3 ]b=[2 4 3]c=[5 2 1]v=dot(a,cross(b,c))4.)数组排序,sort(x) %默认升序Y=sort(X,DIM,MODE)%DIM选择用于排列的维,MODE决定了排序的方式ascen升序dsescend降序4.矩阵1.)生成矩阵[] 空矩阵zeros 0矩阵eye 单位矩阵ones 全为1的矩阵tril 或triu 生成上下三角矩阵diag 生成对角矩阵magic 生成魔术方阵%每一行每一列以及每条主对角线的元素之和都相等(2阶除外)rand 生成0-1分布的随机矩阵randn 生成正态分布的随机矩阵vander 生成范德蒙矩阵2.)求矩阵的秩,r=rank(T); %T为矩阵3.)求矩阵的迹, %矩阵主对角线元素的和T=trace(M); %M为矩阵4.)矩阵的变维,reshape(A,2,4);%变为两行四列5.绘图. 点o 圆- 实线-. 点虚线-- 虚线y 黄色k 黑色w 白色b 蓝色g 绿色r 红色c 亮青色m 锰紫色bar 长条图errorbar 图形加上误差范围fplot 较精确的函数图形polar 极座标图hist 累计图rose 极座标累计图stairs 阶梯图stem 针状图fill 实心图feather 羽毛图compass 罗盘图quiver 向量场图plot: x轴和y轴均为线性刻度(Linear scale)loglog: x轴和y轴均为对数刻度(Logarithmic scale)semilogx: x轴为对数刻度,y轴为线性刻度semilogy: x轴为线性刻度,y轴为对数刻度axis([xmin,xmax,ymin,ymax]):函数来调整图轴的范围xlabel('Input Value'):% x轴注解ylabel('Function Value'): % y轴注解title('Two Trigonometric Functions'): % 图形标题legend('y = sin(x)','y = cos(x)'): % 图形注解grid on:% 显示格线可用subplot来同时画出数个小图形於同一个视窗之中:subplot(2,2,1); plot(x, sin(x));subplot(2,2,2); plot(x, cos(x));subplot(2,2,3); plot(x, sinh(x));subplot(2,2,4); plot(x, cosh(x));6.数据的输入与输出1.)从键盘输入数据,A=input(提示信息,选项);其中提示信息为一个提示用户输入什么样的数据的字符串。
matlab课件-M函数⽂件第 6 章 M ⽂件和函数句柄MATLAB 程序可以由较多的MATLAB 指令和多种多样的MATLAB 表达式组成,并循着⼀定的执⾏次序运⾏。
这种程序的扩展名为m ,这就是脚本M ⽂件或函数M ⽂件。
本章系统介绍编写MATLAB 程序时最常⽤到的四种控制结构、M 函数⽂件的构造、主函数、⼦函数以及匿名函数。
最后⼀节专门叙述函数句柄的创建、观察和调⽤。
6.1 MATLAB 控制流作为⼀种计算机编程语⾔,MATLAB 提供了多种⽤于程序流控制的描述关键词(Keyword )。
本节只介绍其中最常⽤的条件控制(if, switch )和循环控制(for, while, continue, break )。
MATLAB 的这些指令与其它语⾔相应指令的⽤法⼗分相似,因此本节只结合MATLAB 给定的描述关键词,对这四种指令进⾏简要的说明。
6.1.1if-else-end 条件控制if-else-end 指令为程序流提供了⼀种分⽀控制,它最常见的使⽤⽅式见表6.1-1。
【例6.1-1】已知函数xx x e xxy x ≤<≤--=+-111113,编写能对任意⼀组输⼊x 值求相应y 值的程序。
(1)function y=exm060101(x)% y=exm060101(x) Function calculate of example 6.1-1n=length(x); for k=1:n if x(k)<-1 y(k)=x(k); elseif x(k)>=1y(k)=exp(1-x(k)); elsey(k)=x(k)^3;endend(2)⽤exm060101命名M程序并存放在当前⽬录下x=[-2,-1.2,-0.4,0.8,1,6]y=exm060101(x)x =-2.0000 -1.2000 -0.4000 0.8000 1.0000 6.0000y =-2.0000 -1.2000 -0.0640 0.5120 1.0000 0.00676.1.2switch-case控制结构【例6.1-2】已知学⽣的名字和百分制分数。
S函数的简介及编写摘自恒润科技S-function的编写1. S函数模板编辑环境进入:在MATLAB主界面中直接输入:edit sfuntmpl即可弹出S函数模板编辑的M文件环境,修改即可。
在MATLAB主界面中直接输入:sfundemos,即可调出S 函数的许多编程例子。
2. S函数模板的相关基础:1)M文件S函数的引导语句为:xtflagfuFunction[psysxstrtsp,,12,...),,,0,],(,S函数默认的四个输入参数:t ,x ,u ,flagS函数默认的四个输出函数:sys ,x0 ,str ,ts各个参数的含义如下:T :代表当前的仿真时间,该输入决定了下一个采样时间;X :表示状态向量,行向量,引用格式:X(1),X(2)U :表示输入向量;Flag :控制在每一个仿真阶段调用哪一个子函数的参数,由SIMULINK在调用时自动取值;Sys :通用的返回变量,返回的数值决定Flag值,mdlUpdates里:列向量,引用格式:Sys(1,1),Sys(2,1);mdlOutputs里:行向量,引用格式:Sys =x.X0 :初始的状态值;列向量,引用格式:X0=[ 0;0;0 ]Str :空矩阵,无具体含义;Ts :包含模块采样时间和偏差的矩阵。
[period, offset]当Ts为-1时,表示与输入信号同采样周期。
2)S函数工作方式:Flag = 0时,调用mdlInitializeSizes函数,定义S函数的基本特性,包括采样时间,连续或者离散状态的初始条件和Sizes数组;Flag = 1时,调用mdlDerivatives函数,计算连续状态变量的微分方程;求所给表达式的等号左边状态变量的积分值的过程。
Flag = 2时,调用mdlUpdate函数,用于更新离散状态,采样时间和主时间步的要求;Flag = 3时,调用mdlOutputs函数,计算S函数的输出;Flag = 4时,调用mdlGetTimeOfNextVarHit函数,计算下一个采样点的绝对时间,这个方法仅仅是使用户在mdlInitializeSize 里说明一个可变的离散采样时间;Flag = 9时,调用mdlTerminate函数,实现仿真任务的结束。
s函数是system Function的简称,用它来写自己的simulink模块。
(够简单吧,^_^,详细的概念介绍大伙看帮助吧)可以用matlab、C、C++、Fortran、Ada 等语言来写,这儿我只介绍怎样用matlab语言来写吧(主要是它比较简单)先讲讲为什么要用s函数,我觉得用s函数可以利用matlab的丰富资源,而不仅仅局限于simulink提供的模块,而用c或c++等语言写的s函数还可以实现对硬件端口的操作,还可以操作windows API等的先介绍一下simulink的仿真过程(以便理解s函数),simulink的仿真有两个阶段:一个为初始化,这个阶段主要是设置一些参数,像系统的输入输出个数、状态初值、采样时间等;第二个阶段就是运行阶段,这个阶段里要进行计算输出、更新离散状态、计算连续状态等等,这个阶段需要反复运行,直至结束。
在matlab的workspace里打edit sfuntmpl(这是matlab自己提供的s函数模板),我们看它来具体分析s函数的结构。
它的第一行是这样的:function [sys,x0,str,ts]=sfuntmpl(t,x,u,flag)先讲输入与输出变量的含义:t是采样时间,x是状态变量,u是输入(是做成simulink模块的输入),flag是仿真过程中的状态标志(以它来判断当前是初始化还是运行等);sys输出根据flag的不同而不同(下面将结合flag来讲sys的含义),x0是状态变量的初始值,str是保留参数(mathworks公司还没想好该怎么用它,嘻嘻,一般在初始化中将它置空就可以了,str=[]),ts是一个1×2的向量,ts(1)是采样周期,ts(2)是偏移量。
下面结合sfuntmpl.m中的代码来讲具体的结构:switch flag, %判断flag,看当前处于哪个状态case 0,[sys,x0,str,ts]=mdlInitializeSizes;flag=0表示处于初始化状态,此时用函数mdlInitializeSizes进行初始化,此函数在sfuntmpl.m的149行我们找到他,在初始化状态下,sys是一个结构体,用它来设置模块的一些参数,各个参数详细说明如下size = simsizes;%用于设置模块参数的结构体用simsizes来生成sizes.NumContStates = 0;%模块连续状态变量的个数sizes.NumDiscStates = 0;%模块离散状态变量的个数sizes.NumOutputs = 0;%模块输出变量的个数sizes.NumInputs = 0;%模块输入变量的个数sizes.DirFeedthrough = 1;%模块是否存在直接贯通(直接贯通我的理解是输入能%直接控制输出)sizes.NumSampleTimes = 1;%模块的采样时间个数,至少是一个sys = simsizes(sizes); %设置完后赋给sys输出举个例子,考虑如下模型:dx/dt=fc(t,x,u) 也可以用连续状态方程描述:dx/dt=A*x+B*ux(k+1)=fd(t,x,u) 也可以用离散状态方程描述:x(k+1)=H*x(k)+G*u(k)y=fo(t,x,u) 也可以用输出状态方程描述:y=C*x+D*u设上述模型连续状态变量、离散状态变量、输入变量、输出变量均为1个,我们就只需改上面那一段代码为:(一般连续状态与离散状态不会一块用,我这儿是为了方便说明)sizes.NumContStates=1;sizes.NumDiscStates=1;sizes.NumOutputs=1;sizes.NumInputs=1;其他的可以不变。
Matlab中S-函数的使⽤sfuntmpl function [sys,x0,str,ts,simStateCompliance] = sfuntmpl(t,x,u,flag)%SFUNTMPL General MATLAB S-Function Template% With MATLAB S-functions, you can define you own ordinary differential% equations (ODEs), discrete system equations, and/or just about% any type of algorithm to be used within a Simulink block diagram.%% The general form of an MATLAB S-function syntax is:% [SYS,X0,STR,TS,SIMSTATECOMPLIANCE] = SFUNC(T,X,U,FLAG,P1,...,Pn)%% What is returned by SFUNC at a given point in time, T, depends on the% value of the FLAG, the current state vector, X, and the current% input vector, U.%% FLAG RESULT DESCRIPTION% ----- ------ --------------------------------------------% 0 [SIZES,X0,STR,TS] Initialization, return system sizes in SYS,% initial state in X0, state ordering strings% in STR, and sample times in TS.% 1 DX Return continuous state derivatives in SYS.% 2 DS Update discrete states SYS = X(n+1)% 3 Y Return outputs in SYS.% 4 TNEXT Return next time hit for variable step sample% time in SYS.% 5 Reserved for future (root finding).% 9 [] Termination, perform any cleanup SYS=[].%%% The state vectors, X and X0 consists of continuous states followed% by discrete states.%% Optional parameters, P1,...,Pn can be provided to the S-function and% used during any FLAG operation.%% When SFUNC is called with FLAG = 0, the following information% should be returned:%% SYS(1) = Number of continuous states.% SYS(2) = Number of discrete states.% SYS(3) = Number of outputs.% SYS(4) = Number of inputs.% Any of the first four elements in SYS can be specified% as -1 indicating that they are dynamically sized. The% actual length for all other flags will be equal to the% length of the input, U.% SYS(5) = Reserved for root finding. Must be zero.% SYS(6) = Direct feedthrough flag (1=yes, 0=no). The s-function% has direct feedthrough if U is used during the FLAG=3% call. Setting this to 0is akin to making a promise that% U will not be used during FLAG=3. If you break the promise% then unpredictable results will occur.% SYS(7) = Number of sample times. This is the number of rows in TS.%%% X0 = Initial state conditions or [] if no states.%% STR = State ordering strings which is generally specified as [].%% TS = An m-by-2 matrix containing the sample time% (period, offset) information. Where m = number of sample% times. The ordering of the sample times must be:%% TS = [00, : Continuous sample time.% 01, : Continuous, but fixed in minor step% sample time.% PERIOD OFFSET, : Discrete sample time where% PERIOD > 0 & OFFSET < PERIOD.% -20]; : Variable step discrete sample time% where FLAG=4is used to get time of% next hit.%% There can be more than one sample time providing% they are ordered such that they are monotonically% increasing. Only the needed sample times should be% specified in TS. When specifying more than one% sample time, you must check for sample hits explicitly by% seeing if% abs(round((T-OFFSET)/PERIOD) - (T-OFFSET)/PERIOD)% is within a specified tolerance, generally 1e-8. This% tolerance is dependent upon your model's sampling times% and simulation time.%% You can also specify that the sample time of the S-function% is inherited from the driving block. For functions which% change during minor steps, this is done by% specifying SYS(7) = 1 and TS = [-10]. For functions which% are held during minor steps, this is done by specifying% SYS(7) = 1 and TS = [-11].%% SIMSTATECOMPLIANCE = Specifices how to handle this block when saving and% restoring the complete simulation state of the% model. The allowed values are: 'DefaultSimState',% 'HasNoSimState' or 'DisallowSimState'. If this value% is not speficified, then the block's compliance with% simState feature is set to 'UknownSimState'.% Copyright 1990-2010 The MathWorks, Inc.%% The following outlines the general structure of an S-function.%switch flag,%%%%%%%%%%%%%%%%%%% Initialization %%%%%%%%%%%%%%%%%%%case0,[sys,x0,str,ts,simStateCompliance]=mdlInitializeSizes;%%%%%%%%%%%%%%%% Derivatives %%%%%%%%%%%%%%%%case1,sys=mdlDerivatives(t,x,u);%%%%%%%%%%% Update %%%%%%%%%%%case2,sys=mdlUpdate(t,x,u);%%%%%%%%%%%% Outputs %%%%%%%%%%%%case3,sys=mdlOutputs(t,x,u);%%%%%%%%%%%%%%%%%%%%%%%% GetTimeOfNextVarHit %%%%%%%%%%%%%%%%%%%%%%%%case4,sys=mdlGetTimeOfNextVarHit(t,x,u);%%%%%%%%%%%%%% Terminate %%%%%%%%%%%%%%case9,sys=mdlTerminate(t,x,u);%%%%%%%%%%%%%%%%%%%%% Unexpected flags %%%%%%%%%%%%%%%%%%%%%otherwiseDAStudio.error('Simulink:blocks:unhandledFlag', num2str(flag));end% end sfuntmpl%%============================================================================= % mdlInitializeSizes% Return the sizes, initial conditions, and sample times for the S-function.%============================================================================= %function [sys,x0,str,ts,simStateCompliance]=mdlInitializeSizes%% call simsizes for a sizes structure, fill it in and convert it to a% sizes array.%% Note that in this example, the values are hard coded. This is not a% recommended practice as the characteristics of the block are typically% defined by the S-function parameters.%sizes = simsizes;sizes.NumContStates = 0;sizes.NumDiscStates = 0;sizes.NumOutputs = 0;sizes.NumInputs = 0;sizes.DirFeedthrough = 1;sizes.NumSampleTimes = 1; % at least one sample time is neededsys = simsizes(sizes);%% initialize the initial conditions%x0 = [];%% str is always an empty matrix%str = [];%% initialize the array of sample times%ts = [00];% Specify the block simStateCompliance. The allowed values are:% 'UnknownSimState', < The default setting; warn and assume DefaultSimState% 'DefaultSimState', < Same sim state as a built-in block% 'HasNoSimState', < No sim state% 'DisallowSimState' < Error out when saving or restoring the model sim statesimStateCompliance = 'UnknownSimState';% end mdlInitializeSizes%%=============================================================================% mdlDerivatives% Return the derivatives for the continuous states.%=============================================================================%function sys=mdlDerivatives(t,x,u)sys = [];% end mdlDerivatives%%=============================================================================% mdlUpdate% Handle discrete state updates, sample time hits, and major time step% requirements.%=============================================================================%function sys=mdlUpdate(t,x,u)sys = [];% end mdlUpdate%%=============================================================================% mdlOutputs% Return the block outputs.%=============================================================================%function sys=mdlOutputs(t,x,u)sys = [];% end mdlOutputs%%=============================================================================% mdlGetTimeOfNextVarHit% Return the time of the next hit for this block. Note that the result is% absolute time. Note that this function is only used when you specify a% variable discrete-time sample time [-20] in the sample time array in% mdlInitializeSizes.%=============================================================================%function sys=mdlGetTimeOfNextVarHit(t,x,u)sampleTime = 1; % Example, set the next hit to be one second later.sys = t + sampleTime;% end mdlGetTimeOfNextVarHit%%=============================================================================% mdlTerminate% Perform any end of simulation tasks.%=============================================================================%function sys=mdlTerminate(t,x,u)sys = [];% end mdlTerminateS-函数的⼏个概念:1)直接馈通在编写S-函数时,初始化函数中需要对sizes.DirFeedthrough进⾏设置,如果输出函数mdlOutputs或者对于变采样时间的mdlGetTimeOfNextVarHit是输⼊u的函数,则模块具有直接馈通的特性sizes.DirFeedthrough=1;否则为0。
函数是system Function的简称,用它来写自己的simulink模块。
(够简单吧,^_^,详细的概念介绍大伙看帮助吧)可以用matlab、C、C++、Fortran、Ada等语言来写,这儿我只介绍怎样用matlab 语言来写吧(主要是它比较简单)。
先讲讲为什么要用s函数,我觉得用s函数可以利用matlab的丰富资源,而不仅仅局限于simulink 提供的模块,而用c或c++等语言写的s函数还可以实现对硬件端口的操作,还可以操作windows API 等的。
先介绍一下simulink的仿真过程(以便理解s函数),simulink的仿真有两个阶段:一个为初始化,这个阶段主要是设置一些参数,像系统的输入输出个数、状态初值、采样时间等;第二个阶段就是运行阶段,这个阶段里要进行计算输出、更新离散状态、计算连续状态等等,这个阶段需要反复运行,直至结束。
在matlab的workspace里打edit sfuntmpl(这是matlab自己提供的s函数模板),我们看它来具体分析s函数的结构。
它的第一行是这样的:function [sys,x0,str,ts]=sfuntmpl(t,x,u,flag) .先讲输入与输出变量的含义:t是采样时间,x是状态变量,u是输入(是做成simulink模块的输入),flag 是仿真过程中的状态标志(以它来判断当前是初始化还是运行等);sys输出根据flag的不同而不同(下面将结合flag来讲sys的含义),x0是状态变量的初始值,str是保留参数(mathworks公司还没想好该怎么用它,嘻嘻,一般在初始化中将它置空就可以了,str=[]),ts是一个1×2的向量,ts(1)是采样周期,ts(2)是偏移量。
下面结合sfuntmpl.m中的代码来讲具体的结构:switch flag, %判断flag,看当前处于哪个状态case 0,[sys,x0,str,ts]=mdlInitializeSizes;flag=0表示处于初始化状态,此时用函数mdlInitializeSizes进行初始化,此函数在sfuntmpl.m 的149行,我们找到他,在初始化状态下,sys是一个结构体,用它来设置模块的一些参数,各个参数详细说明如下size = simsizes;%用于设置模块参数的结构体用simsizes来生成sizes.NumContStates = 0;%模块连续状态变量的个数sizes.NumDiscStates = 0;%模块离散状态变量的个数sizes.NumOutputs = 0;%模块输出变量的个数sizes.NumInputs = 0;%模块输入变量的个数sizes.DirFeedthrough = 1;%模块是否存在直接贯通(直接贯通我的理解是输入能%直接控制输出)sizes.NumSampleTimes = 1;%模块的采样时间个数,至少是一个sys = simsizes(sizes); %设置完后赋给sys输出举个例子,考虑如下模型:dx/dt=fc(t,x,u) 也可以用连续状态方程描述:dx/dt=A*x+B*ux(k+1)=fd(t,x,u) 也可以用离散状态方程描述:x(k+1)=H*x(k)+G*u(k)y=fo(t,x,u) 也可以用输出状态方程描述:y=C*x+D*u设上述模型连续状态变量、离散状态变量、输入变量、输出变量均为1个,我们就只需改上面那一段代码为:(一般连续状态与离散状态不会一块用,我这儿是为了方便说明)sizes.NumContStates=1;sizes.NumDiscStates=1;sizes.NumOutputs=1;sizes.NumInputs=1;其他的可以不变。