Writing S-Functions | ![]() ![]() |
A Simple M-File S-Function Example
The easiest way to understand how S-functions work is to look at a simple example. This block takes an input scalar signal, doubles 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 with Simulink. By using this template, you can create an M-file S-function that is very close in appearance to a C MEX S-function. This is useful because it makes a transition from an 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.
Below are the S-function subroutines that timestwo.m
calls.
%==============================================================
% Function mdlInitializeSizes initializes the states, sample
% times, state ordering strings (str), and sizes structure.
%==============================================================
function [sys,x0,str,ts] = mdlInitializeSizes
% Call function simsizes to create the sizes structure.
sizes = simsizes;
% Load the sizes structure with the initialization information.
sizes.NumContStates= 0;
sizes.NumDiscStates= 0;
sizes.NumOutputs= 1;
sizes.NumInputs= 1;
sizes.DirFeedthrough=1;
sizes.NumSampleTimes=1;
% Load the sys vector with the sizes information.
sys = simsizes(sizes);
%
x0 = []; % No continuous states
%
str = []; % No state ordering
%
ts = [-1 0]; % Inherited sample time
% End of mdlInitializeSizes.
%==============================================================
% Function mdlOutputs performs the calculations.
%==============================================================
function sys = mdlOutputs(t,x,u)
sys = 2*
u;
% End of mdlOutputs.
To test this S-function in Simulink, connect a sine wave generator to the input of an S-Function block. Connect the output of the S-Function block to a Scope. Double-click on the S-Function block to open the dialog box.
You can now run this simulation.
![]() | Defining S-Function Block Characteristics | Examples of M-File S-Functions | ![]() |