一.S函数简介

在Matlab编程中,涉及复杂的多输入输出编程时,S函数为使用率极高的一个函数,其能很好的完成Matlab和Simulink的联合仿真,下面将使用matlab R2019b展开详细的讲解。

二.Simulink中的S-Function函数

首先打开Simulink

双击空白页面,会出现
输入S-Function,即可的到,点开该模块

输入sfuntmp1,选择Edit,在Matlab内编程即可,sfuntmp为Matlab软件自带的模板,打开修改即可,具体代码如下[1]。

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 0 is 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 = [0      0,      : Continuous sample time.
%                     0      1,      : Continuous, but fixed in minor step
%                                      sample time.
%                     PERIOD OFFSET, : Discrete sample time where
%                                      PERIOD > 0 & OFFSET < PERIOD.
%                     -2     0];     : Variable step discrete sample time
%                                      where FLAG=4 is 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 = [-1 0]. For functions which
%               are held during minor steps, this is done by specifying
%               SYS(7) = 1 and TS = [-1 1].
%
%      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 %%%%%%%%%%%%%%%%%%%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 %%%%%%%%%%%%%%%%%%%%%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  = [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%
%=============================================================================
% 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 [-2 0] 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 mdlTerminate

然后照着模板修改即可

三.参考内容

[1] Matlab中S函数官方模板

Matlab编程算法中S函数的使用方法相关推荐

  1. A*算法中启发函数的使用

    A*算法使用启发函数h(n)来获得对于从任意结点n走到目标结点的最小代价的估计,因此选用一个好的启发函数是非常重要的. A*算法中启发函数的使用 启发函数可以用来控制A*算法的行为. 在极端情况下,如 ...

  2. c语言 编程 函数声明,C语言编程开发中的函数声明与定义

    函数功能的使用在许多编程开发语言中都是有不同的使用方法的,而今天我们就一起来了解一下,在C语言编程开发中的函数功能使用与定义. 对函数的"定义"和"声明"不是一 ...

  3. php中icon,php中iconv函数的使用方法

    本篇文章中的内容介绍的是php中iconv函数的使用方法,在这里分享给大家,有需要的朋友可以参考一下 最近在做一个程序,需要用到iconv函数把抓取来过的utf-8编码的页面转成gb2312, 发现只 ...

  4. Python中range函数的使用方法

    Python中range函数的使用方法 更新时间:2022年05月30日 11:38:15   作者:Python编程学习圈 这篇文章主要介绍了Python中range函数的使用方法,文章基于Pyth ...

  5. Excel中Sumproduct函数的使用方法

    1.sumproduct函数的含义 1 1.Sumproduct函数的适用范围,在给定的几组数组中,然后把数组间对应的元素相乘,最后返回乘积之和. 从字面上可以看出,sumproduct有两个英文单词 ...

  6. 计算机中函数counta表示,excel中counta函数的使用方法

    你还在为Excel中counta函数的使用方法而苦恼吗,今天小编教你Excel中counta函数的使用方法,今天,学习啦小编就教大家在counta函数的使用方法. Excel的counta函数的使用方 ...

  7. php excel 函数,php实现excel中rank函数功能的方法

    php实现excel中rank函数功能的方法 发布于 2015-10-28 18:54:25 | 77 次阅读 | 评论: 0 | 来源: 网友投递 PHP开源脚本语言PHP(外文名: Hyperte ...

  8. php中函数的使用方法,php中header()函数的使用方法

    本文主要和大家分享php中header()函数的使用方法,主要以代码的方式和大家讲解,希望能帮助到大家.跳转页面 header('Location:'.$url); //Location和" ...

  9. 计算机一级vlookup函数的使用方法,电子档Excel中vlookup函数的使用方法(图解详细说明)...

    摘要: 在平时的工作中,相信很多问题在学校学习的难以用在工作当中,但是没学习到的知识点倒是出现在了我们的工作中,本文我将给大家以生动的图解(偷笑)加说明的方式详细介绍Excel中vlookup函数的使 ...

最新文章

  1. Cell:无症状新冠患者阳性持续105天
  2. 四则运算APP最后阶段
  3. 卸载shockwave flash插件
  4. 2020 年腾讯新增 20 亿行代码,鹅厂第一编程语言还是它
  5. spring mvc @RequestBody @ResponseBody 解析流程
  6. java date 转integer_java 中Date的各种格式转换
  7. java 里面matches什么意思_Java Regex中的matches()和find()之间的区别
  8. LNMP环境搭建 centos7 nginx1.12 mysql5.6 php7
  9. 镜头的分类及选购指南
  10. 【社会/人文】概念的理解 —— 断舍离、饭(饭制版)
  11. django 笔记3
  12. mysql中计算月份函数_MySQL几个计算时间的函数汇总
  13. Multisim14简介与安装
  14. 第1章第10节:如何使用PowerPoint的视图功能 [PowerPoint精美幻灯片实战教程]
  15. linux shell运用16进制计算
  16. Matlab-CSMA_CA,pure ALOHA,时隙ALOHA协议性能对比分析仿真
  17. ChineseBERT: Chinese Pretraining Enhanced by Glyph and Pinyin Information
  18. 如何描述缺陷(Defect)?
  19. 每日一练:第十一天——侦探推理
  20. PHP使用swagger-php自动生成api文档(详细附上完整例子)

热门文章

  1. 干货!基于部分-整体关系的概念、关系和物理场景认知推理
  2. 信捷xd5接线图_信捷XD5E系列以太网通讯型PLC
  3. 每日新闻摘要,19/4/10:随着Exodus投放iOS设备,间谍软件不仅适用于Android
  4. ENVI_基于环境小卫星的草原荒漠化监测
  5. SpringBoot中使用AMQ的两种方式二(Java配置、注解方式)
  6. ArcGIS Pro 共享地图(MPKX)
  7. 如何成为一名成功的博士生(计算机科学(in NLPML))——Do what will make you happy
  8. Android中arm64-v8a、armeabi-v7a、armeabi是什么?
  9. 侠义型性格分析,侠义型人格的职业方向
  10. 1.2 Architectural Fundamentals