matlab编写s函数,求解

真的不好意思麻烦大家了,这是关于simulink的第三个问题了,非常感谢之前诸位高手的支持,照例悬赏200,能者多得嘛

貌似用到了模板,求函数主体部分,当然能完整最好了

就这个模型而言,我看不出使用S函数实现有什么好处。

 

如果用S函数实现,会涉及到一些具体的问题:

1、这些常数是在S函数中直接定义,还是要求可以在外部修改(例如在基本工作区中定义)?

2、是否需要把输入独立出来?mg项与状态无关,原则上可以作为一个输入处理,但也可以直接放在S函数里面。

3、初值是否要求从外部指定?

这几个方面的问题都是可以解决的,但取决于要求高低,实现的复杂程度不一样。

 

这里姑且按照最简单的情况来处理,即:

1、常数直接在S函数内部定义;

2、把m*g作为系统模型的一部分,不视为输入,而直接放在S函数中;

3、初值直接在S函数中,不从外部指定。

 

参考代码(只列出修改了的mdlInitializeSizes、mdlDerivatives和mdlOutputs三个函数,其它代码与模板sfuntmpl中的内容完全相同):

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  = 2;
sizes.NumDiscStates  = 0;
sizes.NumOutputs     = 1;
sizes.NumInputs      = 0;
sizes.DirFeedthrough = 0;
sizes.NumSampleTimes = 1;   % at least one sample time is needed
sys = simsizes(sizes);
%
% initialize the initial conditions
%
x0  = [0; 0];
%
% str is always an empty matrix
%
str = [];
%
% initialize the array of sample times
%
ts  = [0 0];

% 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 state
simStateCompliance = 'UnknownSimState';
% end mdlInitializeSizes

function sys=mdlDerivatives(t,x,u)
k=5;
a1=1;
a2=1;
g=10;
m=70;
f = -k*x(1) * (x(1)>0);
sys = [x(2); (m*g+f-a1*x(2)-a2*x(2)*abs(x(2)))/m];
% end mdlDerivatives  

function sys=mdlOutputs(t,x,u)
sys = x(1);
% end mdlOutputs

温馨提示:答案为网友推荐,仅供参考
相似回答