利用SFunction实现传递函数.docx
《利用SFunction实现传递函数.docx》由会员分享,可在线阅读,更多相关《利用SFunction实现传递函数.docx(14页珍藏版)》请在冰豆网上搜索。
![利用SFunction实现传递函数.docx](https://file1.bdocx.com/fileroot1/2023-2/1/ffbb5692-a761-4c80-8721-6f1d4711f49b/ffbb5692-a761-4c80-8721-6f1d4711f49b1.gif)
利用SFunction实现传递函数
利用S-Function实现传递函数
引言
自然界大多数的过程都可以看做是一个系统,一般来说系统都会有输入和输出,而传递函数就是输入到输出的一个转换方式,比如,对于一个罐体来说,流量是输入,液位是输出,则从流量转换到液位的过程就是传递函数的本质,可以通过求解方程式,来确定传递函数的数学形式,也可以通过实验法来辨识这个数学模型。
S-Function的功能就不多说了,总之,其功能之强大,属MATLAB/Simulink开发者必学之内容。
这篇短文讲述的就是如何利用S-Function实现传递函数:
我们知道S-Function有自己的模板,而我们要做的就是更改模板代码中的某些参数就行了,考虑到这些参数和状态方程的关系密切,因此,本文的思路就是首先将传递函数转为系统状态方程,然后再对参数进行修改。
1、MATLAB函数命令介绍
1.1MATLABtf函数命令:
建立传递函数:
例1:
s=tf('s');
H=s/(s^2+2*s+10);
例2:
h=tf([10],[1210]);
1.2MATLABss函数命令:
建立状态空间模型
连续模型:
sys=ss(a,b,c,d)createsastate-spacemodelobjectrepresentingthecontinuous-timestate-spacemodel
ForamodelwithNxstates,Nyoutputs,andNuinputs:
aisanNx-by-Nxreal-orcomplex-valuedmatrix.
bisanNx-by-Nureal-orcomplex-valuedmatrix.
cisanNy-by-Nxreal-orcomplex-valuedmatrix.
disanNy-by-Nureal-orcomplex-valuedmatrix.
TosetD=0,setdtothescalar0(zero),regardlessofthedimension.
离散模型:
sys=ss(a,b,c,d,Ts)createsthediscrete-timemodel
withsampletimeTs(inseconds).SetTs=-1orTs=[]toleavethesampletimeunspecified.
1.3MATLABtf2ss函数命令:
将传递函数模型转化为状态空间模型,单输入单输出系统转换如下:
利用该命令不仅可以转换SISO系统也可以转换MIMO系统,如下MISO系统也可以:
den=[023;121];
num=[10.41];
[A,B,C,D]=tf2ss(den,num)
结果:
A=
-0.4000-1.0000
1.00000
B=
1
0
C=
2.00003.0000
1.60000
D=
0
1
2、实例仿真
2.1假设工业过程某传递函数:
den=[1.5];
num=[151];
[A,B,C,D]=tf2ss(den,num)
结果:
a=
x1x2
x1-5-1
x210
b=
u1
x11
x20
c=
x1x2
y101.5
d=
u1
y10
所以有:
2.2修改S-Function模板参数:
从结果可以看出,系统有两个状态,没有离散状态,输入1个,输出1个,无直通反馈,一种采用时间,打开模板,复制代码。
function[sys,x0,str,ts,simStateCompliance]=sfuntmpl(t,x,u,flag)【一个主函数,需修改原函数名:
sfuntmpl】
%SFUNTMPLGeneralMATLABS-FunctionTemplate
%WithMATLABS-functions,youcandefineyouownordinarydifferential
%equations(ODEs),discretesystemequations,and/orjustabout
%anytypeofalgorithmtobeusedwithinaSimulinkblockdiagram.
%
%ThegeneralformofanMATLABS-functionsyntaxis:
%[SYS,X0,STR,TS,SIMSTATECOMPLIANCE]=SFUNC(T,X,U,FLAG,P1,...,Pn)
%
%WhatisreturnedbySFUNCatagivenpointintime,T,dependsonthe
%valueoftheFLAG,thecurrentstatevector,X,andthecurrent
%inputvector,U.
%
%FLAGRESULTDESCRIPTION
%-------------------------------------------------------
%0[SIZES,X0,STR,TS]Initialization,returnsystemsizesinSYS,
%initialstateinX0,stateorderingstrings
%inSTR,andsampletimesinTS.
%1DXReturncontinuousstatederivativesinSYS.
%2DSUpdatediscretestatesSYS=X(n+1)
%3YReturnoutputsinSYS.
%4TNEXTReturnnexttimehitforvariablestepsample
%timeinSYS.
%5Reservedforfuture(rootfinding).
%9[]Termination,performanycleanupSYS=[].
%
%
%Thestatevectors,XandX0consistsofcontinuousstatesfollowed
%bydiscretestates.
%
%Optionalparameters,P1,...,PncanbeprovidedtotheS-functionand
%usedduringanyFLAGoperation.
%
%WhenSFUNCiscalledwithFLAG=0,thefollowinginformation
%shouldbereturned:
%
%SYS
(1)=Numberofcontinuousstates.
%SYS
(2)=Numberofdiscretestates.
%SYS(3)=Numberofoutputs.
%SYS(4)=Numberofinputs.
%AnyofthefirstfourelementsinSYScanbespecified
%as-1indicatingthattheyaredynamicallysized.The
%actuallengthforallotherflagswillbeequaltothe
%lengthoftheinput,U.
%SYS(5)=Reservedforrootfinding.Mustbezero.
%SYS(6)=Directfeedthroughflag(1=yes,0=no).Thes-function
%hasdirectfeedthroughifUisusedduringtheFLAG=3
%call.Settingthisto0isakintomakingapromisethat
%UwillnotbeusedduringFLAG=3.Ifyoubreakthepromise
%thenunpredictableresultswilloccur.
%SYS(7)=Numberofsampletimes.ThisisthenumberofrowsinTS.
%
%
%X0=Initialstateconditionsor[]ifnostates.
%
%STR=Stateorderingstringswhichisgenerallyspecifiedas[].
%
%TS=Anm-by-2matrixcontainingthesampletime
%(period,offset)information.Wherem=numberofsample
%times.Theorderingofthesampletimesmustbe:
%
%TS=[00,:
Continuoussampletime.
%01,:
Continuous,butfixedinminorstep
%sampletime.
%PERIODOFFSET,:
Discretesampletimewhere
%PERIOD>0&OFFSET%-20];:
Variablestepdiscretesampletime
%whereFLAG=4isusedtogettimeof
%nexthit.
%
%Therecanbemorethanonesampletimeproviding
%theyareorderedsuchthattheyaremonotonically
%increasing.Onlytheneededsampletimesshouldbe
%specifiedinTS.Whenspecifyingmorethanone
%sampletime,youmustcheckforsamplehitsexplicitlyby
%seeingif
%abs(round((T-OFFSET)/PERIOD)-(T-OFFSET)/PERIOD)
%iswithinaspecifiedtolerance,generally1e-8.This
%toleranceisdependentuponyourmodel'ssamplingtimes
%andsimulationtime.
%
%YoucanalsospecifythatthesampletimeoftheS-function
%isinheritedfromthedrivingblock.Forfunctionswhich
%changeduringminorsteps,thisisdoneby
%specifyingSYS(7)=1andTS=[-10].Forfunctionswhich
%areheldduringminorsteps,thisisdonebyspecifying
%SYS(7)=1andTS=[-11].
%
%SIMSTATECOMPLIANCE=Specificeshowtohandlethisblockwhensavingand
%restoringthecompletesimulationstateofthe
%model.Theallowedvaluesare:
'DefaultSimState',
%'HasNoSimState'or'DisallowSimState'.Ifthisvalue
%isnotspeficified,thentheblock'scompliancewith
%simStatefeatureissetto'UknownSimState'.
%Copyright1990-2010TheMathWorks,Inc.
%$Revision:
1.18.2.5$
%
%ThefollowingoutlinesthegeneralstructureofanS-function.
%
switchflag,
%%%%%%%%%%%%%%%%%%
%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);
%%%%%%%%%%%%%%%%%%%%
%Unexpectedflags%
%%%%%%%%%%%%%%%%%%%%
otherwise
DAStudio.error('Simulink:
blocks:
unhandledFlag',num2str(flag));
end
%endsfuntmpl
%
%=============================================================================
%mdlInitializeSizes
%Returnthesizes,initialconditions,andsampletimesfortheS-function.
%=============================================================================
%
function[sys,x0,str,ts,simStateCompliance]=mdlInitializeSizes
%
%callsimsizesforasizesstructure,fillitinandconvertittoa
%sizesarray.
%
%Notethatinthisexample,thevaluesarehardcoded.Thisisnota
%recommendedpracticeasthecharacteristicsoftheblockaretypically
%definedbytheS-functionparameters.
%
sizes=simsizes;【不要更改】
sizes.NumContStates=2;【包括x1和x2两个连续状态】
sizes.NumDiscStates=0;【无离散状态】
sizes.NumOutputs=1;【一个输入u】
sizes.NumInputs=1;【一个输出y】
sizes.DirFeedthrough=0;【y和u无关】
sizes.NumSampleTimes=1;%atleastonesampletimeisneeded【一个采用周期时间,可有多个】
sys=simsizes(sizes);【不要更改】
%
%initializetheinitialconditions
%
x0=[0;0];【初始状态均为0】
%
%strisalwaysanemptymatrix
%
str=[];【系统预留参数,不要更改】
%
%initializethearrayofsampletimes
%
ts=[00];【采样时间和偏移量,都为0说明为连续无偏移】
%SpecifytheblocksimStateCompliance.Theallowedvaluesare:
%'UnknownSimState',%'DefaultSimState',%'HasNoSimState',%'DisallowSimState'simStateCompliance='UnknownSimState';
%endmdlInitializeSizes
%
%=============================================================================
%mdlDerivatives
%Returnthederivativesforthecontinuousstates.
%=============================================================================
%
functionsys=mdlDerivatives(t,x,u)【求导,输出为状态x的导数】
sys=[-5-1;10]*x+[1;0]*u;
%endmdlDerivatives
%
%=============================================================================
%mdlUpdate
%Handlediscretestateupdates,sampletimehits,andmajortimestep
%requirements.
%=============================================================================
%
functionsys=mdlUpdate(t,x,u)【离散情况下的x(n+1)】
sys=[];
%endmdlUpdate
%
%=============================================================================
%mdlOutputs
%Returntheblockoutputs.
%=============================================================================
%
functionsys=mdlOutputs(t,x,u)【系统输出y】
sys=1.5*x
(2);
%endmdlOutputs
%
%=============================================================================
%mdlGetTimeOfNextVarHit
%Returnthetimeofthenexthitforthisblock.Notethattheresultis
%absolutetime.Notethatthisfunctionisonlyusedwhenyouspecifya
%variablediscrete-timesampletime[-20]inthesampletimearrayin
%mdlInitializeSizes.
%=============================================================================
%
functionsys=mdlGetTimeOfNextVarHit(t,x,u)
sampleTime=1;%Example,setthenexthittobeonesecondlater.
sys=t+sampleTime;
%endmdlGetTimeOfNextVarHit
%
%=============================================================================
%mdlTerminate
%Performanyendofsimulationtasks.
%=============================================================================
%
functionsys=mdlTerminate(t,x,u)
sys=[];
%endmdlTerminate