使用M-文件编写S-函数,实现正余弦波的叠加。
编写m文件:sinAddcos.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);
function sys = mdlGetTimeOfNextVarHit(t, x, u)
sampleTime = 1;
sys = t + sampleTime;
function sys = mdlTerminate(t, x,u)
sys = [];
simulink建模与验证(同一文件目录下添加sinAddcos.m文件):