MATLAB/simulink S-函数编程实践

M-文件 S-函数编写实例:实现两个正余弦函数叠加合成。

simulink自带S-函数模板,在MATLAB/toolbox/simulink/blocks/sfuntmpl.m 目录

以简单加法器为例内容如下:

function[sys, x0, str, ts] = sinAddcos(t,x,u,flag)
%% Create a s function to add the sine wave and cosine wave
% t         --simulated time
% x         --inner simulated block
% u         --simulated output
% flag      --operation flage
% sys       --S function output
% x0        --S function initial states
% str       --temp empty vector
% ts        --(2 X 2)time sample matrix,[:,1] sampling time and [:,2] time shifting
 
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);
  otherwise
        error(['Unhandled flag = ', num2str(flag)])
end
 
function [sys, x0, str, ts] = mdlInitializeSizes
sizes = simsizes;
sizes.NumContStates = 0;
sizes.NumDiscStates = 1;
sizes.NumOutputs = 1;
sizes.NumInputs = 2;
sizes.DirFeedthrough = 1;
sizes.NumSampleTimes = 1;
sys = simsizes(sizes);
x0 = [0];
str = [];
ts = [0 0];
 
function sys = mdlDerivatives(t, x, u)
        sys = [];
function sys = mdlUpdate(t, x, u)
        sys = x;
function sys = mdlOutputs(t, x, u)
        sys = u(1) + u(2);                            %output = u_1 + u_2
function sys = mdlGetTimeOfNextVarHit(t, x, u)
        sampleTime = 1;
        sys = t + sampleTime;
function sys = mdlTerminate(t, x,u)
        sys = [];

 

你可能感兴趣的:(MATLAB)