User`s guide

2 Writing S-Functions As M-Files
2-4
A Simple M-File S-Function Example
The easiest way to understand how S-functions work is to look at a simple
example. T h is block takes an input scalar sign al, d oubles it, and plots it to a
scope:
The M-file code that contains the S-function is modeled on an S-function
template called
sfuntmpl.m, which is included wit h Simulink. By using this
template, you can create an M-file S-function tha t is very close in appearance
toaCMEXS-function.Thisisusefulbecauseitmakesatransitionfroman
M-file to a C MEX-file much easier.
Below is the M-file code for the
timestwo.m S-function:
function [sys,x0,str,ts] = timestwo(t,x,u,flag)
% Dispatch the flag. The switch function controls the calls to
% S-function routines at each simulation stage.
switch flag,
case 0
[sys,x0,str,ts] = mdlInitializeSizes; % Initialization
case 3
sys = mdlOutputs(t,x,u); % Calculate outputs
case { 1, 2, 4, 9 }
sys = []; % Unused flags
otherwise
error(['Unhandled flag = ',num2str(flag)]); % Error handling
end;
% End of function timestwo.