Mathworks SIMULINK 7 Developing S-Functions

Simulink
®
7
Developing S-Functions
How to Contact The MathWorks
www.mathworks. comp.soft-sys.matlab Newsgroup www.mathworks.com/contact_TS.html T echnical Support
suggest@mathworks.com Product enhancement suggestions bugs@mathwo doc@mathworks.com Documentation error reports service@mathworks.com Order status, license renewals, passcodes info@mathwo
com
rks.com
rks.com
Web
Bug reports
Sales, prici
ng, and general information
508-647-7000 (Phone)
508-647-7001 (Fax)
The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site.
Developing S-Functions
© COPYRIGHT 1998–20 10 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathW orks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through the federal government of the United States. By accepting delivery of the Program or Documentation, the government hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand Documentation by the federal government (or other entity acquiring for or through the federal government) and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the government’s needs or is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Docu mentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
October 1998 First printing Revised for Version 3.0 (Release R11) November 2000 Second printing Revised for Version 4.0 (Release R12) July 2002 Third printing Revised for Version 5.0 R elease R13) April 2003 Online only Revised for Version 5.1 (Release R 13SP1) April 2004 Online only Revised for Version 5.1.1 (Release R13SP1+) June 2004 Online only Revised for Version 6.0 (Release R14) October 2004 Online only Revised for Version 6.1 (Release R14SP1) March 2005 Online only Revised for Version 6.2 (Release R 14SP2) September 2005 Online Only Revised for Version 6.3 (Release R 14SP3) March 2006 Online only Revised for Version 6.4 (Release 2006a) September 2006 Online only Revised for Version 6.5 (Release 2006b) March 2007 Online only Revised for Version 6.6 (Release 2007a) September 2007 Online only Revised for Version 7.0 (Release 2007b) March 2008 Online only Revised for Version 7.1 (Release 2008a) October 2008 Online only Revised for Version 7.2 (Release 2008b) March 2009 Online only Revised for Version 7.3 (Release 2009a) September 2009 Online only Revised for Version 7.4 (Release 2009b) March 2010 Online only Revised for Version 7.5 (Release 2010a)
1
Contents
Overview of S-Functions
What Is an S-Fun
Using S-Funct
Overview Passing Para When to Use an
How S-Funct
Introduct Mathemati Simulatio S-Functio
Implemen
M-File S MEX-Fil
S-Func
tion Con cepts
Direct Dynami Setti
Feedthrough
ng Sample Times and Offsets
ions in Models
........................................ 1-3
meters to S-Functions
ions Work
ion
......................................
cs of Simulink Blocks nStages n Callback Methods
ting S-Functions
-Functions e S-Functions
cally Sized Arrays
ction?
.............................
........................
...................
S-Function
.........................
.............................
.....................
.................................
.......................
.........................
................................
.............................
...............................
................................
..........................
....................
1-2
1-3
1-5 1-6
1-7 1-7 1-7 1-8 1-9
1-11 1-11 1-12
1-14 1-14 1-15 1-16
S-Fun
ction Examples
iew of Examples
Overv
l-2 M-File S- Function Examples
Leve
l-1 M-File S- Function Examples
Leve
unction Examples
CS-F
tran S-Function Examples
For
S-Function Examples
C++
..............................
..............................
..................
..................
............................
.......................
..........................
1-21 1-21 1-23 1-23 1-25 1-2 1-3
9 0
v
Selecting an S-Function Implementation
2
Available S-Function Implementations .............. 2-2
What Type of S-Function Should You Use?
How to Implement S-Functions
S-Function Features
S-Function Limitations
Example Using S-Functions to Incorporate Legacy C
Code
Overview Using a Hand-Written S-Function to Incorporate Legacy
Using the S-Function Builder to Incorporate Legacy
Using the Legacy Code Tool to Incorporate Legacy Code
........................................... 2-14
........................................ 2-14
Code
.......................................... 2-15
Code
.......................................... 2-17
............................... 2-8
............................. 2-12
..................... 2-5
Writing S-Functions in M
3
........... 2-3
.. 2-22
vi Contents
Introduction ...................................... 3-2
Writing Level-2 M-File S-Functions
About Lev el-2 M-File S-Functions About Run-Time Objects Level-2 M-File S-Function Template Level-2 M-File S-Function Callback M ethods Using the Example of Writing a Level-2 M-File S-Function Instantiating a Level-2 M-File S-Function Operations for Variable-Size Signals Generating C ode from a Level-2 M-File S-Function
setup Method ............................ 3-8
............................ 3-5
.................. 3-4
.................... 3-4
.................. 3-5
........... 3-6
........ 3-8
............. 3-12
.................. 3-12
...... 3-13
M-File S-Function Demos ........................... 3-13
Maintaining Level-1 M-File S-Functions
About the Maintenance of Level-1 M-File S-Functions Level-1 M-File S-Function Arguments Level-1 M-File S-Function Outputs Defining S-Function Block Characteristics Processing S-Function Parameters Converting Level-1 M-File S-Functions to Level-2
................... 3-16
................... 3-18
............. 3-14
................ 3-15
............. 3-17
....... 3-18
Writing S-Functions in C
4
Introduction ...................................... 4-2
About Writing C S-Functions Creating C MEX S-Functions
Building S-Functions Automatically
About Building S-Functions Automatically Deploying the Generated S-Function How the S-Function Builder Builds an S-Function
........................ 4-2
........................ 4-3
................. 4-5
............. 4-5
.................. 4-10
...... 4-11
... 3-14
S-Function Builder Dialog Box
About S-Function Builder Parameters/S-Function Name Pane Port/Parameter Pane Initialization Pane Data Properties Pane Input Ports Pane Output Ports Pane Parameters Pane Data Type Attributes Pane Libraries Pane Outputs Pane Continuous Derivatives Pane Discrete Update Pane Build Info Pane Example: Modeling a Two-Input/Two-Output System
.................................... 4-24
..................................... 4-27
.............................. 4-15
................................ 4-16
.............................. 4-18
.................................. 4-19
................................ 4-21
.................................. 4-22
.............................. 4-33
................................... 4-34
...................... 4-12
........................... 4-12
................... 4-14
.......................... 4-23
........................ 4-31
.... 4-37
vii
Example of a Basic C MEX S-Function ............... 4-43
Introducing an Example of a Basic C MEX S-Function Defines and Includes Callback Method Implementations Simulink/Real-Time Workshop Interfaces Building the Timestwo Example
............................... 4-46
................... 4-46
.............. 4-48
..................... 4-49
... 4-43
Templates for C S-Functions
About the Templates for C S-Functions S-Function Source File Requirements The SimStruct Data Types in S-Functions Compiling C S-Functions
Integrating Existing C Functions into Simulink Models
with the Legacy C ode Tool
Overview Example of Integrating Existing C Functions into Simulink
Models with the Legacy Code Tool Registering Legacy Code Tool Data Structures Declaring Legacy Code Tool Function Specifications Generating and Compiling the S-Functions Generating a Masked S-Function Block for Calling a
Generated S-Function Forcing Simulink
TLC Inlining Code Calling Legacy C++ Functions Handling Multiple Registration Files Deploying Generated S-Functions Legacy Code Tool Demos Legacy Code Tool Limitations
.................................... 4-53
........................................ 4-55
®
Accelerator Mode to Use S-Function
.............................. 4-73
........................ 4-50
................ 4-50
................. 4-50
.......................... 4-53
........................... 4-53
....................... 4-55
.................. 4-58
.......... 4-62
..... 4-64
............ 4-71
............................ 4-72
....................... 4-73
................. 4-74
.................... 4-75
........................... 4-75
....................... 4-75
viii Contents
How the Simulink Engine Interacts w ith C
S-Functions
Introduction Process View Data View
Writing Callback Methods
Using S-Functions in Normal Mode Referenced
Models
..................................... 4-77
...................................... 4-77
..................................... 4-77
....................................... 4-85
.......................... 4-90
......................................... 4-91
Debugging C MEX S-Functions ...................... 4-93
About Debugging C MEX S-Functions Debugging C MEX S-Functions in the Simulink
Environment
Debugging C MEX S-Functions Using Third-Pa r ty
Software
................................... 4-93
....................................... 4-98
................. 4-93
Converting Level-1 C M EX S-Functions to Level-2
Guidelines for Converting Level-1 C MEX S-Functions to
Level-2
Obsolete Macros
........................................ 4-102
.................................. 4-105
Creating C++ S -Functions
5
Creating a C++ Source File ......................... 5-2
Making C++ Objects Persistent
Building C++ S-Functions
..................... 5-3
.......................... 5-5
Creating Fortran S-Functions
6
.... 4-102
Level-1 Versus Level-2 S-Functions .................. 6-2
Creating Level-1 Fortran S-Functions
Fortran M EX Template File Example of a Level-1 Fortran S-Function Inline Code Generation Example
Creating Level-2 Fortran S-Functions
About Creating Level-2 Fortran S-Functions Template File
.................................... 6-8
......................... 6-3
..................... 6-6
............... 6-3
.............. 6-3
............... 6-8
........... 6-8
ix
C/Fortran Interfacing Tips .......................... 6-8
Constructing the Gateway Example C MEX S-Function Calling Fortran Code
.......................... 6-13
...... 6-16
PortingLegacyCode
Find the States Sample Times Store Data Use Flints if Needed Considerations for Real Time
....................................... 6-19
............................... 6-18
................................... 6-18
.................................... 6-19
............................... 6-19
........................ 6-20
Using Work Vectors
7
About DWork Vectors .............................. 7-2
What is a DWork Vector? Advantages of DWork Vectors DWork Vectors and the Simulink Engine DWork Vectors and the Real-Time Workshop Product
Types of DWork Vectors
How to Use DW ork Vectors
Using DWork Vectors in C MEX S-Functions DWork Vector C MEX Macros Using DWork Vectors in Level-2 M-File S-Functions Using DWork Vectors to Pass Data Between
S-Functions Using DWork Vectors With Legacy Code
.................................... 7-14
........................... 7-2
....................... 7-2
.............. 7-3
............................ 7-5
......................... 7-7
........... 7-7
....................... 7-10
.............. 7-17
.... 7-4
..... 7-12
x Contents
DWork Vector Examples
General DWork Vector DWork S cratch Vector DState Work Vector DWork Mode Vector Level-2 M -File S-Function DWork Vector
Elementary Work Vectors
........................... 7-18
............................. 7-18
............................. 7-20
............................... 7-22
............................... 7-24
.......................... 7-29
.............. 7-27
Description of Elementary Work Vector ............... 7-29
Relationship to DWork Vectors Using Elementary Work Vectors Additional Work Vector Macros Elementary Work Vector Examples
...................... 7-29
..................... 7-30
...................... 7-32
................... 7-33
Implementing Block Features
8
Dialog Parameters ................................. 8-2
About Dialog Parameters Tunable Parameters
........................... 8-2
............................... 8-5
Run-Time Parameters
About Run-Time Parameters Creating Run-Time Parameters Updating Run-Time Parameters Tuning Run-Time Parameters Accessing Run-Time Parameters
Input a nd Output Ports
Creating Input Ports for C S-Functions Creating Input Ports for Level-2 M-File S-Functions Creating Output Ports for C S-Functions Creating Output Ports for Level-2 M-File S-Functions Scalar Expansion of Inputs Masked Multiport S-Functions
Custom Data Types
Using Custom Data Types in C S-Functions Using Custom Data Types in Level-2 M-File S-Functions
Sample Times
About Sample Times Block-Based Sample Times Specifying Port-Based Sample Times Hybrid Block -Bas ed and Port-Based Sample Times Multirate S-Function Blocks
..................................... 8-33
.............................. 8-8
........................ 8-8
...................... 8-9
..................... 8-15
....................... 8-17
..................... 8-17
............................ 8-19
................ 8-19
.............. 8-25
.......................... 8-26
....................... 8-28
................................ 8-29
............ 8-29
............................... 8-33
......................... 8-34
................. 8-38
........................ 8-45
..... 8-23
... 8-26
.. 8-30
...... 8-44
xi
Multirate S-Functions and Sample Time Hit
Calculations Synchronizing Multirate S-Function Blocks Specifying Model Reference Sample Time Inheritance
.................................... 8-47
............ 8-47
.... 8-48
Zero Crossings
S-Function Compliance with the
SimState Compliance Specification for Level-2 M-File
S-Functions
SimState Compliance Specification for C-MEX
S-Functions
Matrices in C S-Functions
MX A rray Manipulation Memory Allocation
Function-Call Subsystems
Sim Viewing Devices in External Mode
Frame-Based Signals
About Frame-Based Signals Using F rame-Based Signals in C S-Functions Using Frame-Based Signals in Level-2 M-File
S-Functions
.................................... 8-51
SimState ............ 8-55
.................................... 8-55
.................................... 8-56
.......................... 8-58
............................ 8-58
................................ 8-59
.......................... 8-60
.............. 8-65
............................... 8-66
......................... 8-66
.......... 8-66
.................................... 8-68
xii Contents
Error Handling
About Handling Errors Exception Free Code ssSetErrorStatus Termination Criteria Checking Array Bounds
C MEX S-Function Examples
About S-Function Examples Continuous States Discrete States Continuous and Discrete States Variable Sample Time Array Inputs and Outputs
.................................... 8-69
............................. 8-69
............................... 8-70
............................ 8-72
........................ 8-73
......................... 8-73
................................. 8-73
................................... 8-80
............................. 8-94
.......................... 8-100
................ 8-71
...................... 8-87
9
10
Zero-Crossing Detection ............................ 8-112
Discontinuities in Continuous States
................. 8-129
S-Function Callback Methods — Alphabetical
List
SimStruct Funct ions Reference
Introduction ...................................... 10-2
About SimStruct Functions Language Support The SimStruct
................................. 10-2
.................................... 10-2
......................... 10-2
SimStruct Macros and Functions Listed by Usage
Buses Data Type Dialog Bo x Parameters Error Handling and Status Function Call Input and Output Ports Model Reference Run-Time Parameters Sample Time Simulation Information State and Work Vector Code Generation Miscellaneous
........................................... 10-4
....................................... 10-5
............................. 10-6
.......................... 10-7
..................................... 10-7
............................ 10-8
.................................. 10-15
.............................. 10-16
..................................... 10-17
............................ 10-18
............................. 10-21
.................................. 10-24
.................................... 10-26
.... 10-4
xiii
11
A
S-Function Options — Alphabetical List
Examples
S-Function Features ............................... A-2
S-Function Examples
Writing S-Functions in M
S-Function Builder
Writing S-Functions in C
Creating Fortran S-Functions
Using Work Vectors
.............................. A-2
........................... A-2
................................ A-2
........................... A-2
................................ A-3
...................... A-3
Index
xiv Contents

Overview of S-Functions

“What Is an S-Function?” on page 1-2
“Using S-Functions in Models” on page 1-3
“How S-Functions Work” on page 1-7
“Implementing S-Functions” on page 1-11
“S-Function Concepts” on page 1-14
“S-Function Examples” on page 1-21
1
1 Overview of S-Functions

What Is an S-Function?

S-functions (system-functions) provide a powerful mechanism for extending the capabilities of the Simulink language description of a Simulink block written in MATLAB Fortran. C, C ++, and Fortran S-functions a re compiled as MEX-files using the
mex utility (see “Building MEX-Files” in MATLAB External Interfaces). As
with other MEX-files, S-f unctions are dynamically linked subroutines tha t the MATLAB interpreter can automatically load and execute.
S-functions use a special calling syntax called the S-function API that enables you to interact with the Simulink engine. This interaction is very similar to the interaction that takes place between the engine and built-in Simulink blocks.
S-functions follow a general form and can accommodate continuous, discrete, and hybrid systems. By following a set of simple rules, you can implement an algorithm in an S-function and use the S-Function block to add it to a Simulink model. After you write your S-functio n and place its name in an S-Function block (available in the User-Defined Functions block library), you can customize the user interface using masking (see “Creating Custom Blocks”).
You can use S-functions with the Real-Time Workshop customize the code generated for S-functions by writing a Target Language Compiler (TLC) file. See “Integrating Externa l Code With Gen erated C and C++ Code” in the Real-Time Workshop User’s Guide for more information.
®
environment. An S-function is a computer
®
®
, C, C++, or
product. You can also
1-2

Using S-Functions in Models

In this section...
“Overview” on page 1-3
“Passing Parameters to S-Functions” on page 1-5
“When to Use an S-Function” on page 1-6

Overview

To incorporate a C MEX S-function or legacy Level-1 M-file S-function into a Simulink model, drag an S-Function block from the User-Defined Functions block library into the model. Then specify the name o f the S-function in the S-function name field of the S-Function block’s Block Parameters dialog box, as illustrated in the following figure.
Using S-Functions in Models
1-3
1 Overview of S-Functions
1
Constant
/* * File : timestwo.c * Abstract: * An example C-file S-function for * multiplying an input by 2: * y = 2*u */
timestwo
S−Function
2
Display
1-4
In this example, the model contains an S-Function block that references an instance of the C MEX-file for the S-function
timestwo.c.
Note If the MATLAB path includes a C MEX-file and an M-file having the same name referenced by an S-Function block, the S-Function block uses the C MEX-file.
Using S-Functions in Models
To incorporate a Level-2 M-file S-function into a model, drag a Level-2 M-file S-Function block from the User-Defined Functions library into the model. Specify the name of the S-function in the M-file name field.

Passing Parameters to S-Functions

The S-Function block’s S-function parameters and Level-2 M-file S-Function block’s Parameters fields allow you to specify parameter values to pass to the corresponding S-function. To use these f ields, you must know the param eters the S-function requires and the order in w hich the function re quires them. (If you do n ot know, consult the S-function’s author, documentation, or source code.) Enter the parameters, separated by a comma, in the order required by the S-function. The parameter values can be constants, names of variables defined in the MATLAB or model workspace, or MATLAB expressions.
The following example illustrates usage of the Parameters field to enter user-defined parameters for a Level-2 M-file S-fu nction.
1-5
1 Overview of S-Functions
The model in this example incorporates the sample S-function
matlabroot/toolbox/simulink/blocks/msfcn_limintm.m
The msfcn_limintm.m S-function accepts three parameters: a lower bound, an upper bound, and an initial condition. The S-function outputs the time integraloftheinputsignalifthetimeintegralisbetweenthelowerandupper bounds, the lower bound if the time integral is less than the lower bound, and the upper bound if the time integral is greater than the upper bound. The dialog box in the example sp ecifies a lower and upper bound and an initial condition of whentheinputisasinewaveofamplitude1.
See “Processing S-Function Parameters” on page 3-18 and “Error Handling” on page 8-69 for information on how to access user-specified parameters in an S-function.
You can use the masking facility to create custom dialog boxes and icons for your S-Function blocks. Masked dialog boxes can make it easier to specify additional parameters for S-functions. For a discussion on masking, see “Working with Block Masks” in Using Simulink.
2, 3,and2.5, respectively. The scope shows the resulting output
1-6

When to Use an S-Function

You can use S-functions for a variety of applications, including:
Creating new general purpose blocks
Adding blocks that represent hardware device drivers
Incorporating existing C code into a simulation (see “Integrating Existing C
Functions into Simulink Models with the Legacy Code Tool” on page 4-55)
Describing a system as a set of mathematical equations
Using graphical animations (see the inverted pendulum demo,
The most common use of S-functions is to create custom Simulink blocks (see “Creating Custom Blocks” in Using Simulink). When you use an S-function to create a general-purpose block, you can use it many times in a model, varying parameters with each instance of the block.
penddemo)

How S-Functions Work

In this section...
“Introduction” on page 1-7
“Mathematics of Simulink Blocks” on page 1-7
“Simulation Stages” on page 1-8
“S-Function Callback Methods” on page 1-9

Introduction

To create S-functions, you need to understand how S-functions work. Such knowledge requires an understanding of how the Simulink engine simulates a model, including the mathematics o f blocks. This section begin s by e xplaining the mathematical relationships between the inputs, states, and outputs of ablock.
How S-Functions Work

Mathematics of Simulink Blocks

A Simulink block consists of a set of inputs, a set of states, and a set of outputs, where the outputs are a function of the simulation time, the inputs, and the states.
The following equations express the mathematical relationships between the inputs, outputs, states, and simulation time
yftxu
=
(, , )
0
xftxu
=
d
ducd
kk+=1
where
xxx
(Outputs)
(, , )
 (Derivatives)
(, , , ),
= [; ].
cd
(Update)xftxxu
1-7
1 Overview of S-Functions
Simulation Stag
Execution of a Si initialization blocks into the evaluates bloc memory. The en the loop is ref theengineexe initializat block states
The followi integratio The engine e for the sta the simula Simulink f See “How t a d escrip and simul
ion. For each block, the engine invokes functions that compute the
n loop takes place only if the model contains continuous states.
te computations. The entire simulation loop then continues until
tion is co mplete. See “Simulating Dynamic Systems” in Using or more detailed information on howtheengineexecutesamodel.
he Simulink Engine Interacts with C S-Functions” on page 4-77 for
tion of how the engine calls the S-function API during initialization
ation.
mulink model proceeds in stages. First comes the
phase. In this phase, the Simulink engine incorporates library
model, propagates signal widths, data types, and sample times,
k parameters, determines block execution order, and allocates
gine then enters a simulation loop, where each pass through
erred to as a simulation step. During each simulation step,
cutes each block in the model in the order determined during
, derivatives, and outputs for the current sample time.
ng figure illustrates the stages of a simulation. The inner
xecutesthisloopuntilthesolver reaches the desired accuracy
es
1-8
How S-Functions Work
How the Simulink®Engine Performs Simulation

S-Function Callback Methods

An S-function comprises a set of S-function callback methods that perform tasks required at each simulation stage. During simulation of a model, at each simulation stage, the Simulink enginecallstheappropriatemethodsfor each S-Function block in the model. Tasks performed by S-function callback methods include:
1-9
1 Overview of S-Functions
Initialization — Prior to the first simulation loop, the engine initializes the
S-function, including:
- Initializing the SimStruct, a simulation structure that contains
information about the S-function
- Setting the number and dimensions of input and output ports
- Setting the block sample times
- Allocating storage areas
Calculation of next sample hit — If you created a variable sample time
block, this stage calculates the time of the next sample hit; that is, it calculates the next step size.
Calculation of outputs in the major time step — After this call is complete,
all the block output ports are valid for the current time step.
Update of discrete states in the major time step — In this call, the block
performs once-pe r-tim e-step activities such as updating discrete states.
Integration — This applies to models with continuous states and/or
nonsampled zero crossings. If your S-function has continuous states, the engine calls the output and derivative portions of your S-function at minor time steps. This is so the solvers can compute the states for your S-function. If your S-function has nonsampled zero crossings, the engine also calls the output and zero-crossings portions of your S-function at minor time steps so that it can locate the zero crossings.
1-10
Note See “How Simulink W orks” in Us ing Simulink for an explanation of major and minor time steps.

Implementing S-Functions

In this section...
“M-File S-Functions” on page 1-11
“MEX-File S-Functions” on page 1-12

M-File S-Functions

Level-2 M-f ile S-functions allow you to create blocks with many of the features and capabilities of Simulink built-in blocks, including:
Multiple input and output ports
The ability to accept vector or matrix signals
Support for various signal attributes including data type, complexity, and
signal frames
Ability to operate at multiple sample rates
Implementing S-Functions
A Level-2 M-file S-function consists of a properties of the S-function, and a number of callback methods that the Simulink engine invokes at appropriate times during the simulation.
A basic annotated version of the template resides at
matlabroot/toolbox/simulink/blocks/msfuntmpl_basic.m
Thetemplateconsistsofatop-levelsetup function and a set of skeleton subfunctions, each of which corresponds to a particular callback method. Each callback method performs a specific S-function task at a particular point in the simulation. The engine invokes the subfunctions using function handles defined in the Methods” on page 3-6 for a table of the supported Level-2 M-file S-function callback methods.
A more detailed Level-2 M-file S-function template resides at
matlabroot/toolbox/simulink/blocks/msfuntmpl.m
setup routine. See “Level-2 M -File S-Function Callback
setup routinetoconfigurethebasic
1-11
1 Overview of S-Functions
We recommend that you follow the structure and naming conventions of the templates when creating Level-2 M-file S-functions. This makes it easier for others to understand and maintain the M-file S-functions that you create. See Chapter 3, “Writing S-Functions in M” for information on creating Level-2 M-file S-functions.

MEX-File S-Functions

Like a Level-2 M-file S-function, a MEX S-function consists of a set of callback methods that the Simulink engine invokes to perform various block-related tasks during a simulation. MEX S-functions can be implemented in C, C++, or Fortran. The engine directly invokes MEX S-function routines instead of using function handles as with M-file S-functions. Because the engine invokes the functions directly, MEX S-functions must follow standard naming conventions specified by the S-function API.
An annotated C MEX-file S-function template resides at
matlabroot/simulink/src/sfuntmpl_doc.c
1-12
The template contains skeleton implementations of all the required and optional callback methods that a C MEX S-function can implement.
For a more basic version of the template see
matlabroot/simulink/src/sfuntmpl_basic.c
MEX-File Versus M-File S-Functions
Level-2 M-file and MEX-file S-functions each have ad vantages. The advantage of Level-2 M-file S-functions is speed of development. Developing Level-2 M-file S-functions avoids the time consuming compile-link-execute cycle required when d eveloping in a compiled language. Level-2 M-file S-functions also have easier access to MATLAB toolbox functions and can utilize the MATLAB Editor/Debugger.
MEX-file S-functions are more appropriate for integrating legacy code into a Simulink model. For more complicated systems, MEX-file S-functions may simulate faster than M-file S-functions because the Lev el-2 M-file S-functio n calls the MATLAB interpreter for every callback method.
Implementing S-Functions
See Chapter 2, “Selecting an S-Function Implementation” for information on choosing the type of S-function best suited for your application.
1-13
1 Overview of S-Functions

S-Function Concepts

In this section...
“Direct Feedthrough” on page 1-14
“Dynamically Sized Arrays” on page 1-15
“Setting Sample Times and O ffsets” on page 1-16

Direct Feedthrough

Direct feedthrough means that the output (or the variable sample time for variable sample time blocks) is controlled directly by the value of an input port signal. Typically, an S-function input port has direct feedthrough if
The output function (
is direct feedthrough if the input can also include graphical outputs, as in the case of an XY Graph scope.
The “time of next hit” function (
sample time S-function accesses the input u.
An example of a system that requires its inputs (that is, has direct feedthrough) is the operation
yku=×,
where u is the input, k is the gain, and y is the output.
An example of a system that does not require its inputs (that is, does not have direct feedthrough) is the simple integration algorithm
yx= ,
xu= ,
where x is the state,
nput, and y is the output. Simulink integrates the variable
i
mdlOutputs) is a function of the input u.Thatis,there
u is accessed by7 mdlOutputs.Outputs
mdlGetTimeOfNextVarHit)ofavariable
x
is the state derivative with respect to time, u is the
x.
1-14
S-Function Concepts
It is very important to set the direct feedthrough flag correctly because it affects the execution order of the blocks in your model and is used to detect algebraic loops (see “Algebraic Loops” in Using Simulink). If the simulation results for a model containing your S-function do not converge, or the simulation fails, you may have the direct feedthrough flag set inco rrectly . Try turning on the direct feedthrough flag and setting the Algebraic loop solver diagnostic to “Diagnostics Pane: Solver” reference page in Simulink G raphical User Interface). Subsequ ently run n i ng the simulation displays any algebraic lo op s in the model and shows if the engine has placed your S-function within an algebraic loop.
warning (see the “Algebraic loop” option on the

Dynamically Sized Arrays

You can write your S-function to support arbitrary input dimensions. In this case, the Simulink engine determines the actual input dimensions when the simulation is started by evaluating the dimensions of the input vectors driving the S-function. Your S-function can also use the input dimensions to determine the number of continuous states, the number of discrete states, and the number of outputs.
Note A dyna m ica lly sized input can have a different size for each instance of theS-functioninaparticularmodelorduring different simulations, however the input size of each instance of the S-function is static over the course of a particular simulation.
A C MEX S-function and Level-2 M-file S-function can have multiple input and output ports and each port can have different dimensions. The number of dimensions and the size of each dimension can be determined dynamically.
For example, the following illustration shows two instances of the same S-Function block in a model.
1-15
1 Overview of S-Functions
The upper S-Function block is driven by a block with a three-element output vector. T he lower S-Function block is driven by a block with a scalar output. By specifying that the S-Function block has dynamically sized inputs, the same S-function can accommodate both situations. The Simulink engine automatically calls the block with the appropriately sized input vector. Similarly, if other block characteristics, such as the number of outputs or the number of discrete or continuous states, are specified as dynamically sized, the engine defines these vectors to be the same length as the input vector.
See “Input and Output Ports” on page 8-19 for more information on configuring S-function input and output ports.
1-16

Setting Sample Times and Offsets

Both Level-2 M-file and C MEX S-functions provide the following sample time options, which allow for a high degree of flexibility in specifying when an S-function executes:
Continuous sample time — For S-functions that have continuous states
and/or nonsampled zero crossings (see “How Simulink Works” in Using Simulink for an explanation of zero crossings). For this type of S-function, the output changes in minor time steps.
Continuous, but fixed in minor time step sample time — For S-functions
that need to execute at every major simulation step, but do not change value during minor time steps.
Discrete sample time — If the behavior of your S-function is a function of
discretetimeintervals,youcandefineasampletimetocontrolwhenthe Simulink engine calls the S-function. You can also define an offset that delays each sample time hit. The valueoftheoffsetcannotexceedthe corresponding sample time.
A sample time hit occurs at time values determined by the formula
S-Function Concepts
TimeHit = (n * period) + offset
where the integer n is the current simulation step. The first value of n is always zero.
If you define a discrete sample time, the engine calls the S-function
mdlOutput and mdlUpdate routines at each sample time hit (as defined
in the p revious equation).
Variable sample time — A discrete sample time where the intervals
between sample hits can vary. At the start of each simulation step, S-functions with variable sample times are queried for the time of the next hit.
Inherited sample time — Sometimes an S-function has no inherent sample
time characteristics (that is, it is either continuous or discrete, depending onthesampletimeofsomeotherblockinthesystem). Inthiscase,you can specify that the sample time is inherited.Asimpleexampleofthisisa Gain block that inherits its sample time from the block driving it.
An S-function can inherit its sample time from
- The driving block
- The destination block
- The fastest sample time in the system
To specify an S-function sample time is inherited, use -1 in Level-2 M-file S-functions and sample time. For more information on the propagation of sample times, see “How Propagation Affects Inherited Sample Times” in the Simulink User’s Guide.
S-functions can be either single or multirate; a multirate S-function has multiple sample times.
Sample times are specified in pairs in this format: [
offset_time
Valid C MEX S-Function Sample Times
The valid sample time pairs for a C ME X S-function are
INHERITED_SAMPLE_TIME in C MEX S-functions as the
sample_time,
].
1-17
1 Overview of S-Functions
[CONTINUOUS_SAMPLE_TIME, 0.0] [CONTINUOUS_SAMPLE_TIME, FIXED_IN_MINOR_STEP_OFFSET]
discrete_sample_time_period, offset]
[ [VARIABLE_SAMPLE_TIME, 0.0]
where
CONTINUOUS_SAMPLE_TIME = 0.0 FIXED_IN_MINOR_STEP_OFFSET = 1.0 VARIABLE_SAMPLE_TIME = -2.0
and variable names in italics indicate that a real value is required.
Alternatively, you can specify that the sample time is inherited from the driving block. In this case, the C MEX S-function has only one sample time pair, either
[INHERITED_SAMPLE_TIME, 0.0]
or
1-18
[INHERITED_SAMPLE_TIME, FIXED_IN_MINOR_STEP_OFFSET]
where
INHERITED_SAMPLE_TIME = -1.0
Valid Level-2 M-File S-Function Sample Times
The valid sample time pairs for a L evel-2 M-file S-function are
[0 offset] % Continuous sample time
discrete_sample_time_period, offset] % Discrete sample time
[ [-1, 0] % Inherited sample time [-2, 0] % Variable sample time
where v ariable names in italics indicate that a real value is required. When using a continuous sample time, an in minor integration time steps. An at every minor integration time step.
offset of 1 indicates the output is fixed offset of 0 indicates the output changes
S-Function Concepts
Guidelines for Choosing a Sample Time
Use the following guidelines for help with specifying sample times:
A continuous S-function that chang es during minor integration steps
should register the [
A continuous S-function that does not change during minor
integration steps should register the
FIXED_IN_MINOR_STEP_OFFSET]
A discrete S-function that changes at a specified rate sh ou l d register the
discrete sample time pair, [ where
discrete_sample_period > 0.0
and
0.0 offset < discrete_sample_period
CONTINUOUS_SAMPLE_TIME, 0.0]sampletime.
[CONTINUOUS_SAMPLE_TIME,
sample time.
discrete_sample_time_period, offset],
A discrete S-function that changes at a variable rate should register the
variable-step discrete sample time.
[VARIABLE_SAMPLE_TIME, 0.0]
In a C MEX S-function, the mdlGetTimeOfNextVarHit routine is called to get the time of the next sample h it for the variabl e-step discrete task. In a Level-2 M -file S-function, the
NextTimeHit property is set in the Outputs
method to set the next sample hit.
If your S-function has no intrinsic sample time, you must indicate that your sample time is inherited. There are two cases:
An S-function that changes as its input changes, even during minor
integration steps, should register the
[INHERITED_SAMPLE_TIME, 0.0]
sample time.
An S-function that changes as its input changes, but does not
change during minor integration steps (that is, remains fixed during minor time steps), should register the
FIXED_IN_MINOR_STEP_OFFSET]
[INHERITED_SAMPLE_TIME,
sample time.
1-19
1 Overview of S-Functions
The Scope block is a good example of this type of block. This block runs at the rate of its driv in g block, either continuous or discrete, but never runs in minor steps. If it did, the scope display would show the intermediate computations of the solver rather than the final result at each time point.
See “Sample Times” on page 8-33 for information on implementing different types of sample times in S-functions.
1-20

S-Function Examples

In this section...
“Overview of Examples” on page 1-21
“Level-2 M-File S-Function Examples” on page 1-23
“Level-1 M-File S-Function Examples” on page 1-23
“C S-Function Examples” on page 1-25
“Fortran S-Function Examples” on page 1-29
“C++ S-Function Examples” on page 1-30

Overview of Examples

Torunanexample:
1 In the MATLAB Command Window, enter sfundemos .
S-Function Examples
The S-function demo library opens.
Each block represents a category of S-function examples.
2 Double-click a category to display the examples that it includes.
1-21
1 Overview of S-Functions
1-22
3 Double-click a block to open and run the example that it represents.
ItmightbehelpfultoexaminesomesampleS-functionsasyoureadthenext chapters. Code for the examples is stored in the following folder under the MATLAB root folder.
M-files
C, C++, and Fortran
toolbox/simulink/simdemos/simfeatures
toolbox/simulink/simdemos/simfeatures/src
S-Function Examples
Level-2 M-File S
The matlabroot/ many Level-2 M-f
-Function Examples
toolbox/simulink/simdemos/simfeatures
ile S-functions. Consider starting off by looking at these files.
Filename Model Name
msfcn_dsc.m msfcndemo_sfundsc1.mdl
msfcn_limintm.m msfcndemo_limintm.mdl
n_vs.m
tirate.m
msfcndemo
msfc
msfcn_mul
msfcn_times_two.m msfcndemo_timestwo.mdl
msfcn_unit_delay.m msfcndemo_sfundsc2.mdl
msfcn_varpulse.m msfcndemo_varpulse.mdl
msfc
_multirate.mdl
ndemo_vsfunc.mdl
folder contains
Description
ImplementanS-functionwithan inherited sample time.
Implement a c integrator bounded by l and include
ontinuous limited
where the output is
ower and upper bounds
s initial conditions.
Implement a multirate system.
Implement an S-function that doubles its input.
Implement a unit delay.
Implem genera withi Also d custo bloc
ent a variable pulse width
tor by calling
set_param from
n a Le vel-2 M-file S-function.
emonstrates how to use
m set and get me thods for the
kSimState.
Implement a variable sample time block in which the first input is delayed by an amount of time determined by the second input.

Level-1 M-File S-Function Examples

The matlabroot/toolbox/simulink/simdemos/simfeatures folder also contains many Level-1 M-file S-functions, provided as reference for legacy models. Most of these Level-1 M-file S-functions do not have associate d demo models.
1-23
1 Overview of S-Functions
Filename Description
csfunc.m
dsfunc.m
limintm.m
mixedm.m
sfun_varargm.m
simom.m
simom2.m
vdlmintm.m
vdpm.m
vlimintm.m
vsfunc.m
Define a continuous system in state-space format.
Define a discrete system in state-space format.
Implement a continuous limited integrator where the output is bounded by lower and upper bounds and includes initial conditions.
Implement a hybrid system consisting of a continuous integrator in series with a unit delay.
Implement an S-function that shows how to use the MATLAB command
Implement a system in state-space format with internal
dx/dt = Ax + By y=Cx+Du
where x is the state vector, u is the input vector, and
y is the output vector. The A, B, C,andD matrices are
embedded in the M-file S-function.
Implement a system in state-space format with external structure is the same as in and to this S-function.
Implement a discrete limited integrator. This example is identical to integrator is discrete.
Implement the Van der Pol equation (similar to the demo model,
Implement a continuous limited integrator. This S-function illustrates how to build an S-function that can accommodate a dynamic input and state width.
Illustrate how to create a variablesampletimeblock. This S-function implements a variable step delay in which the first input is delayed by an amount of time determined by the second input.
varargin.
A, B, C,andD matrices, using the equations
A, B, C,andD matrices. The state-space
simom.m,buttheA, B, C,
D matrices are provided externally as parameters
vlimintm.m, except that the limited
vdp).
1-24
S-Function Examples
CS-FunctionExa
The matlabroot/ contains exampl S-function cou
toolbox/simulink/simdemos/simfeatures/src
es of C MEX S-functions, many of which have an M-file
nterpart. The C M EX S-functions are listed in the following
mples
table.
Filename Model Name Description
barplot.c sfcndemo_barplot.mdl
Access Simulink signals without using the standard block inputs.
csfunc.c sfcndemo_csfunc.mdl
dlimintc.
c
No model available Implement a discrete-time limited
Implement a
integrator.
dsfunc.c sfcndemo_dsfunc.mdl
limintc.c
mixedm
.c
No model
sfcnde
available
mo_mixedm.mdl
Implement a discrete system.
Impleme
nt a limited integrator.
Implement a hybrid dynamic system consisting of a continuous integrator (1/s) in series with a unit delay (1/z).
mixedmex.c sfcndemo_mixedmex.mdl
Implement a hybrid dynamic system with a single output and two inputs.
quantize.c sfcndemo_sfun_quantize.mdl
otproduct.c
sd
fbuilder_bususage.csfbuilder_bususage.mdl
s
sftable2.c
cndemo_sdotproduct.mdl
sf
No model available Implement a two-dimensional table
lement a vectorized quantizer.
Imp
ntizes the input into steps as
Qua
cified by the quantization interval
spe
ameter,
par
mpute dot product
Co
ultiply-accumulate) of two
(m
eal or complex vectors.
r
ccess S-Function Builder with a bus
A
nput and output.
i
lookup.
sfun_atol.c sfcndemo_sfun_atol.mdl
Set different absolute tolerances for each continuous state.
folder
continuous system.
q.
1-25
1 Overview of S-Functions
Filename Model Name Description
sfun_cplx.c sfcndemo_cplx.mdl
sfun_directlook.c
sfun_dtype_io.c sfcndemo_dtype_io.mdl
sfun_dtype_param.c sfcndemo_dtype_param.mdl
sfun_dynsize.c sfcndemo_sfun_dynsize.mdl
sfun_errhdl.c sfcndemo_sfun_errhdl.mdl
sfun_fcncall.c sfcndemo_sfun_fcncall.mdl
sfun_frmad.c sfcndemo_frame.mdl
sfun_frmda.c sfcndemo_frame.mdl
sfun_frmdft.c sfcndemo_frame.mdl
sfun_frmunbuff.c sfcndemo_frame.mdl
sfun_multiport.c sfcndemo_sfun_multiport.mdl
sfun_manswitch.c
sfun_matadd.c sfcndemo_matadd.mdl
No model available Implement a direct 1-D lookup.
No model available Implement a manual switch.
Add complex data for an S-function with one input port and one parameter.
Implement an S-function that uses Simulink data types for inputs and outputs.
Implement an S-function that uses Simulink data types for parameters.
Implements dynamically-sized outputs .
Check parameters using the
mdlCheckParameters S-function
routine.
Execute function-call subsystems on thefirstandsecondoutputelements.
Implement a frame-based A/D converter.
Implement a frame-based D/A converter.
Implement a multichannel frame-based Discrete-Fourier transformation (and its inverse).
Implement a frame-based unbuffer block.
Configure multiple input and output ports.
Add matrices in an S-function with one input port, one output port, and one parameter.
1-26
Filename Model Name Description
sfun_multirate.c sfcndemo_sfun_multirate.mdl
Demonstrate h ow to specify port-based sample times.
sfun_port_constant.c sfcndemo_port_constant.mdl
Demonstrate how to specify constant port-based sample times.
sfun_port_triggered.c sfcndemo_port_triggered.mdl
Demonstrate how to use port-based sample times in a triggered subsystem.
sfun_runtime1.c sfcndemo_runtime.mdl
Implement run-time parameters for all tunable parameters.
sfun_runtime2.c sfcndemo_runtime.mdl
Register individual run-time parameters.
sfun_runtime3.c sfcndemo_runtime.mdl
Register dialog parameters as run-time parameters.
sfun_runtime4.c sfcndemo_runtime.mdl
Implement run-time parameters as a function of multiple dialog parameters.
sfun_simstate.c sfcndemo_sfun_simstate.mdl
Demonstrate the S-function API for saving and restoring the SimState.
sfun_zc.c sfcndemo_sfun_simstate.mdl
Demonstrate use of nonsampled zero crossings to implement S-function is designed to be used with a variable-step solver.
sfun_zc_sat.c sfcndemo_sfun_zc_sat.mdl
Demonstrate zero crossings with saturation.
sfunmem.c sfcndemo_sfunmem.mdl
Implement a one-integration-step delay and hold memory function.
S-Function Examples
abs(u).This
1-27
1 Overview of S-Functions
Filename Model Name Description
simomex.c sfcndemo_simomex.mdl
stspace.c sfcndemo_stspace.mdl
stvctf.c sfcndemo_stvctf.mdl
stvdtf.c sfcndemo_stvdtf.mdl
stvmgain.c sfcndemo_stvmgain.mdl
Implement a single-input, two-output state-space dynamic system described by the state-space equations:
where x is the state vector, u is vector of inputs, and of outputs.
Implement a set of state-space equations. You can turn this into a new block by using the S-Function block and mask facility. This example MEX-fileperformsthesamefunction as the built-in State-Space block. This is an example of a MEX-file where the number of inputs, outputs, and states is dependent on the parameters passed in from the workspace.
Implement a continuous-time transfer function whose transfer function polynomials are passed in via the input vector. This is useful for continuous time adaptive control applications.
Implement a discrete-time transfer function whose transfer function polynomials are passed in v ia the input vector. This is useful for discrete-time adaptive control applications.
Implement a time-varying matrix gain.
dx/dt = Ax + Bu y=Cx+Du
y is the vector
1-28
Filename Model Name Description
table3.c
timestwo.c sfcndemo_timestwo.mdl
No model available Implement a 3-D lookup table.
Implement a C MEX S-function that doubles its input.
vdlmintc.c
No model available Implement a discrete-time vectorized
limited integrator.
vdpmex.c sfcndemo_vdpmex.mdl
vlimintc.c
No model available Implement a vectorized limited
Implement the Van der Pol equation.
integrator.
vsfunc.c sfcndemo_vsfunc.mdl
Illustrate how to create a variable sample time block. This block implements a variable-step delay in which the first input is delayed by an amount of time determined by the second input.
S-Function Examples

FortranS-FunctionExamples

The following table lists sample Fortran S-functions available in the
matlabroot/toolbox/simulink/simdemos/simfeatures/src folder.
Filename Model Name Description
sfun_timestwo_for.F sfcndemo_timestwo_for.mdl
sfun_atmos.c sfun_atmos_sub.F
simomexf.F
vdpmexf.F
sfcndemo_atmos.mdl
No model available Implement a Level-1 Fortran
No model available Implement a Level-1 Fortran
Implement a Level-1 Fortran S-function that represents the
timestwo.c S-function.
Calculate the 1976 standard atmosphere to 86 km using a Fortran subroutine.
S-function that represents the
simomex.c S-function.
S-function that represents the
vdpmex.c S-function.
1-29
1 Overview of S-Functions
C++ S-Function E
The following ta
matlabroot/too
Filename Model Name Description
sfun_counter_cpp.cpp sfcndemo_counter_cpp.mdl
ble lists sample C++ S-functions available in the
lbox/simulink/simdemos/simfeatures/src
xamples
Store a C++ object in the pointers vector
PWork.
folder.
1-30

Selecting an S-Function Implementation

“Available S-Function Implementations” on page 2-2
“What Type of S-Function Should You Use?” on page 2-3
“How to Implement S-Functions” on page 2-5
“S-Function Features” on page 2-8
“S-Function Limitations” on page 2-12
2
“Example Using S-Functions to Incorporate Legacy C Code” on page 2-14
2 Selecting an S-Function Implementation

Available S-Function Implementations

YoucanimplementyourS-functioninoneoffiveways:
A Level-1 M-file S-function providesasimpleMinterfacetointeract
with a small portion of the S-function API. Level-2 M-file S-functions supersede Level-1 M-file S-functions.
A Level-2 M-file S-function provides access to a more extensive set of the
S-function A PI and supports code generation. In m o st cases, u se a Lev el-2 M-file S-function when you want to implement your S-function in M.
A handwritten C MEX S-function provides the most programming
flexibility. You can implement your algorithm as a C MEX S-function or write a wrapper S-function to call existing C, C++, or Fortran code. Writing a new S-functio n requires knowledge of the S-function API and, if you want to generate inlined code for the S-function, the Target Language Compiler (TLC).
The S-Function Builder is a graphical user interface for programming
a subset of S-function functionality. If you are new to writing C MEX S-functions, you can use the S-Function Builder to generate new S-functions or incorporate existing C or C++ code without interacting with the S-function API. The S-Function Builder can also generate TLC files for inlining your S-function during code generation with the Real-Time Workshop product.
2-2
The Legacy Code Tool is a set of MATLAB commands that helps
you create an S-function to incorporate legacy C or C ++ code. Like the S-Function Builder, the Legacy Code Tool can generate a TLC file to inline your S-function during code generation. The Legacy Code Tool provides access to fewer of the methods in the S-function API than the S-Function Builder or a handwritten C MEX S-function.
The following sections describe the uses, features, and differences of these S-function implementations. The last section compares using a handwritten C MEX S-function, the S-Function Builder, and the Legacy Code Tool to incorporate an existing C function into your Simulink model.

What Type of S-Function Should You Use?

Consider the following questions if you are unclear about what type of S-functionisbestforyourapplication.
What Type of S-Function Should You Use?
If you...
AreanMprogrammerwithlittleornoC programming experience
Need to generate code for a model containing the S-function
Need the simulation to run faster A C MEX S-function, even if you do not need
Need to implement the S-function in C, but have no previous experience writing C MEX S-functions
Are incorporating legacy code into the model Any S-function, with the exception of a
Then us e.. .
A Level-2 M-file S-function, especially if you do not need to generate code for a model containing the S-function (see Chapter 3, “Writing S-Functions in M”).
Either a Level-2 M-file S-function or a C MEX S-functions. Level-2 M-file S-functions require that you write a Target Language Compiler (TLC) file for your S-function, before generating code. C MEX S-functions, however, automatically support code generation.
to generate code (see Chapter 4, “Writing S-Functions in C”). For complicated systems, Level-2 M-file S-functions simulate slower than C MEX S-functions because they call out to the MATLAB interpreter.
The S-Function Builder.
Level-1 M-file S-function. Consider using the Legacy Code Tool if your legacy function calculates only outputs, not dynamic states (see “Integrating Existing C Functions into Simulink M odels with the Legacy Code Tool” on page 4-55). Otherwise, consider using the S-Function Builder. If you need to call the legacy code during simulation, do not use a Level-2 M-file S-function because they call legacy code only through their TLC files.
2-3
2 Selecting an S-Function Implementation
If you...
Need to generate embeddable code for an S-function that incorporates legacy code
Then us e.. .
The Legacy Code Tool if your legacy function calculates only outputs. Otherwise, use a handwritten C MEX S-function or the S-Function Builder.
2-4

How to Implement S-Functions

The following table gives an overview of how to write different types of S-functions. See the associated sections of the S-function documentation for more details on how to im plement S-functions using a particular method.
Note For backward compatibility, the following table and sections contain information about Level-1 M-file S-functions. However, use the Level-2 M-file S-function API to develop new M-file S-functions.
How to Implement S-Functions
S-Function
Type
Implementation
Level-1 M-file S-function Use the following template to write a new Level-1 M-file S-function:
sfuntmpl.
m
See “Maintaining Level-1 M-File S-Functions” on page 3-14 for more information.
Level-2 M-file S-function
1 Use the following tem plate to write a new Level-2 M-file
S-function:
msfunt
mpl_basic.m
See “Writing Level-2 M-File S-Functions” on page 3-4 for more information.
2 Write
aTargetLanguageCompiler(TLC)filefortheS-functionif
eed to generate code for a model containing the S-function.
you n
ile, msfcn_times_two.tlc in the folder is an example TLC file
The f
he S-function msfcn_times_two.m. See “Inlining MATLAB
for t
S-Functions” in Real-Time Workshop Target Language
File
piler for information on writing TLC files for Level-2 M-file
Com
unctions.
S-f
2-5
2 Selecting an S-Function Implementation
S-Function Type
Hand-written C MEX S-function
S-Function Builder
Implementation
1 UsethefollowingtemplatetowriteanewCMEXS-function(see
“Example of a Basic C MEX S-Function” on page 4-43) or to write a wrapper S-function that calls C, C++, or Fortran code:
matlabroot/simulink/src/sfuntmpl_doc.c
See “Writing Wrapper S-Functions” in the Real-Time Workshop User’s Guide for information on writing w rapper S-functions
to incorporate legacy C or C++ code. See “Constructing the Gateway” on page 6-13 for information on writing a wrapper function to incorporate legacy Fortran code.
2 Compile the S-function using the mex command to obtain an
executable to use during simulation.
3 Write a TLC file for the S-function if you want to inline the code
during code generation (see “Writing Fully Inlined S-Functions with the mdlRTW Routine” in the Real-Time Workshop User’s Guide and Real-Time Workshop Target Language Compiler). You do not need a TLC file if you are not inlining the S-function in the generated code.
1 Enter the S-function attributes into the S-Function B uilder
dialog box (see “S-Function Builder Dialog Box” on page 4-12).
2 Select the Generate wrapper TLC option to generate a TLC
file to inline the S-function during code generation.
3 Click Build to generate the S-function, TLC file, and an
executable file to use during simulation.
Legacy Code Tool Use the legacy_code function to perform the following steps (see
“Integrating Existing C Functions into Simulink Models w ith the Legacy Code Tool” on page 4 -55):
1 Initialize a data structure that describes the S-function
attributes in terms of the legacy function.
2-6
How to Implement S-Functions
S-Function Type
Implementation
lct_spec = legacy_code('initialize');
2 Generate and compile the wrapper S-function.
legacy_code('sfcn_cmex_generate', lct_spec); legacy_code('compile', lct_spec);
3 Instantiate an S-Function block that calls the S-function
wrapper.
legacy_code('slblock_generate', lct_spec);
4 Generate a TLC file to inline the S-function during code
generation.
legacy_code('sfcn_tlc_generate', lct_spec);
2-7
2 Selecting an S-Function Implementation

S-Function Features

The following tables give overviews of the features supported by different types of S-functions. The first table focuses on handwritten S-functions. The second table compares the features of S-functions automatically generated by the S-Function Builder or Legacy Code Tool.

Features of Hand-writte n S-Functions

Feature
Data types
Numeric types
Frame support
Port dimens
S-function API
Code generation support
ions
Level-1 M-File S-Function
Supports signals with a data type of
Supports only real signals. Supports real and
Does not frame-b
Supports vector inputs and outputs. Does not support multiple input and output ports.
Supports only
mdlInitializeSizes, mdlDerivatives, mdlUpdate, mdlOutputs, mdlGetTimeOfNextVarHit,
and
mdlTerminate.
Does not support code generation.
double.
support
ased signals.
Level-2 M-File S-Function
Supports any data type supported by Simulink software, including fixed-point types.
complex signals.
Supports framed and unframed signals.
Supports scalar, 1-D, and multidimensional input and output signals.
Supports a larger set of the S-function API. See “Level-2 M-File S-Function Callback Methods” on page 3-6 for a list of supported methods.
Requires a handwritten TLC file to generate code.
Handwritten C MEX S-Function
Supports any data type supported by Simulink software, including fixed-point types.
Supports real and complex signals.
Supports framed and unframed signals.
Supportsscalar,1-D,and multidimensional input and output signals.
Supports the entire S-function API.
Natively supports code generation. Requires a handwritten TLC file to inline the S-function during code generation.
2-8
Features of Hand-written S-Functions (Continued)
S-Function Features
Feature
Simulink
®
Accelerator™ mode
Model reference
Simulink. AliasType Simulink. NumericType
,
and
Simulink. StructType
support
Bus input and output signals
Level-1 M-File S-Function
Runs interpretively and is, therefore, not accelerated.
Cannot be used in a referenced model.
Does not support these classes.
Does not support bus input or output signals.
Level-2 M-File S-Function
Provides the option to use a TLC file in Accelerator mode, instead of running interpretively.
Supports Normal and Accelerator mode simulations when used in a referenced model. Requires a TLC file for Accelerator mode.
Supports
Simulink.NumericType
and
Simulink.AliasType
classes (see “Custom Data Types” on page 8-29).
Does not support bus input or output signals.
Handwritten C MEX S-Function
Provides the option to use a TLC or MEX-file in Accelerator mode.
Provides options for sample time inheritance and N ormal mode support when used in a referenced model.
Supports all of these classes (see “Custom Data Types” on page 8-29). However, supports
Simulink.StructType
only for S-function parameters.
Does not support bus input or output signals.
Tunable and run-time parameters
Work vectors
Supports tunable parameters during simulation. Does not support run-time parameters.
Does not support work vectors.
Supports tunable and run-time parameters.
Supports DWork vectors (see “Using DWork Vectors in Level-2 M-File S-Functions” on page 7-12).
Supports tunable a nd run-time parameters.
Supports all work vector types (see Chapter 7, “Using W ork Vectors”).
2-9
2 Selecting an S-Function Implementation

Features of Automatically Generated S-Functions

Feature
Data types
S-Function Builder Legacy Code Tool
Supports any data type supported by Simulink software, including fixed-point types.
Numeric types
Supports real and complex signals.
Frame support
Supports framed and unframed signals.
Port dimensions
Supports scalar, 1-D, and multidimensional input and output signals.
S-function API Supports mdlInitializeSizes,
mdlInitializeSampleTimes, mdlStart, mdlDerivative, mdlUpdate, mdlOutput,and mdlTerminate.
Code generation support
Natively supports code generation. Also, automatically generates a TLC file for inlining the S-function during code generation.
Supports all built-in data types. To use a fixed-point data type, you must spe cify the d ata type as a
Simulink.NumericType.You
cannot use a fixed-point type with unspecified scaling.
Supports complex signals only for built-in d ata types.
Does not support frame-based signals.
Supports scalar, 1-D, and multidimensional input and output signals.
Supports
mdlInitializeSampleTimes, mdlStart, mdlInitializeConditions, mdlOutputs,andmdlTerminate.
mdlInitializeSizes,
Natively supports code generation optimized for embedded systems. Also, automatically generates a TLC file that supports expression folding for inlining the S-function during code generation.
Simulink Accelerator mode
Uses a TLC file in Accelerator mode, if the file was generated. Otherwise, uses the MEX-file.
Model reference Uses default behaviors when
used in a referenced model.
2-10
Provides the option to use a TLC or MEX-file in Accelerator mode.
Uses default behaviors when used in a referenced model.
Features of Automatically Generated S-Functions (Continued)
S-Function Features
Feature
Simulink.AliasType, Simulink.NumericType,
S-Function Builder Legacy Code Tool
Does not support these classes.
and
Simulink.StructType
Bus input and output signals
Tunable and run-time parameters
Does not support bus input or output signals.
Supports tunable parameters only during simulation. Supports run-time parameters.
Work vectors Does not provide access to work
vectors.
Supports
Simulink.AliasType
and Simulink.NumericType.
Supports bus input and output signals. Y ou must define a
Simulink.Bus object in the
MATLAB workspace that is equivalent to the structure of the input or output used in the legacy code. Does not support bus parameters.
Supports tunable and run-time parameters.
Supports DWork vectors with the usage type
SS_DWORK_USED_AS_DWORK.
See “Types of DWork Vectors” on page7-5foradiscussiononthe different DWork vector usage types.
2-11
2 Selecting an S-Function Implementation

S-Function Limitations

The following table summarizes the major limitations of the different types of S-functions.
Implementation
Level-1 M-file S-function Does not support the majority o f S-function features. See the
Level-2 M-file S-functions
Handwritten C MEX S-function
S-Funct
ion Builder
Limitations
“S-Function Features” on page 2-8 section for information on what features a L eve l-1 M-file S-function does support.
Does not support bus input and output signals.
Cannot incorporate legacy code during simulation, only
during code generation through a TLC file.
Does not s
Does not s
See “Simu
Simulin
Generat
incurs
Does no
- Work v
- Port-
- Multi
- Dyna
S-fu
upport bus input and output signals.
upport model referencing under all circumstances. link Model Referencing Limitations” in Using
k for details.
es S-function code using a wrapper function which
additional overhead.
t support the following S-function features:
ectors
based sample times
ple sample times or a nonzero offset time
mically-sized input and output signals for an
nction with multiple input and output ports
2-12
gacy Code Tool
Le
e S-functions with one input and one output port can
Not
e dynamically-sized signals
hav
nerates C MEX S-functions for existing functions written
Ge
n C or C++ only. The tool does not support transformation of
i
ATLAB or Fortran functions.
M
S-Function Limitations
Implementation
Limitations
Can interface with C++ functions, but not C++ objects.
Does not support simulating continuous or discrete states.
Does not support use of function pointers as the output o f the
legacy function being called.
Always sets the S-function’s flag for direct feedthrough
sizes.DirFeedthrough)totrue.
(
Supports only the continuous, but fixed in minor time step,
sample time and offset option.
Supports complex numbers, but only with Simulink built-in
data types.
Does not support the following S-function features:
- Work vectors, other then general DWork vectors
- Frame-based input and output signals
- Port-based sample times
- Multiple block-based sample times
2-13
2 Selecting an S-Function Implementation

Example Using S-Functions to Incorporate Legacy C Code

In this section...
“Overview” on page 2-14
“Using a Hand-Written S-Function to Incorporate Legacy Code” on page 2-15
“Using the S-Function Builder to Incorporate Legacy Code” on page 2-17
“UsingtheLegacyCodeTooltoIncorporateLegacyCode”onpage2-22

Overview

C MEX S-functions allow you to call existing C code within your Simulink models. For example, consider the simple C function a value two times the value of the function input.
double doubleIt(double u) {
return(u * 2.0);
}
doubleIt.c that outputs
2-14
You can create an S-function that calls doubleIt.c by either:
Writing a wrapper S-function. U sing this method, you hand write a new
C S-function and associated TLC file. This method requires the most knowledge about the structure of a C S-function.
Using an S-Function Builder block. Using this method, you enter the
characteristics of the S-function into a block dialog. This method does not require any knowledge about writing S-functions. However, a basic understanding of the structure of an S-function can make the S-Function Builder dialog box easier to use.
Using the Legacy Code Tool. Using this command line method, you define
the characteristics of your S-functioninadatastructureintheMATLAB workspace. This method requires the least amount of knowledge about S-functions.
The following sections describe how to create S-functions for use in a Simulink simulation and with Real-Time Workshop code generation, using the previous
Example Using S-Functio ns to Incorporate Legacy C Code
three methods. The model sfcndemo_choosing_sfun.mdl contains blocks that use these S-functions. Copy this model and the files
doubleIt.h from the folder docroot/toolbox/simulink/sfg/examples into
doubleIt.c and
your working folder if you plan to step thro ugh the examples.

Using a Hand-Written S-Function to Incorporate Legacy Code

The S-function wrapsfcn.c calls the legacy function doubleIt.c in its
mdlOutputs method. Save the wrapsfcn.c file into your working folder, if
you are planning to compile the S-function to run in the example model
sfcndemo_choosing_sfun.mdl.
To incorporate the legacy code into the S-function, declaring
extern real_T doubleIt(real_T u);
doubleIt.c with the following line:
Once declared, the S-function can use doubleIt.c in its mdlOutputs method. For example:
/* Function: mdlOutputs =======================================
wrapsfcn.c begins by
2-15
2 Selecting an S-Function Implementation
* Abstract:
* Calls the doubleIt.c function to multiple the input by 2.
*/
static void mdlOutputs(SimStruct *S, int tid){
InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S,0);
real_T *y = ssGetOutputPortRealSignal(S,0);
*y = doubleIt(*uPtrs[0]);
}
To compile the wrapsfcn.c S-function, run the following mex command. Make sure that the
mex wrapsfcn.c doubleIt.c
To generate code for the S-function using the Real-Time Workshop code generator, you need to write a Target Language Compiler (TLC) file. The following TLC file declare a function prototype for then tells the Real-Time Workshop code generator how to inline the call to
doubleIt.c. For example:
doubleIt.c file is in your working folder.
wrapsfcn.tlc uses the BlockTypeSetup function to
doubleIt.c. The TLC file’s Outputs function
2-16
%implements "wrapsfcn" "C"
%% File : wrapsfcn.tlc
%% Abstract:
%% Example tlc file for S-function wrapsfcn.c
%%
%% Function: BlockTypeSetup ================================
%% Abstract:
%% Create function prototype in model.h as:
%% "extern double doubleIt(double u);"
%%
%function BlockTypeSetup(block, system) void
%openfile buffer
%% PROVIDE ONE LINE OF CODE AS A FUNCTION PROTOTYPE
extern double doubleIt(double u);
%closefile buffer
Example Using S-Functio ns to Incorporate Legacy C Code
%<LibCacheFunctionPrototype(buffer)>
%%endfunction %% BlockTypeSetup
%% Function: Outputs =======================================
%% Abstract:
%% CALL LEGACY FUNCTION: y = doubleIt( u );
%%
%function Outputs(block, system) Output
/* %<Type> Block: %<Name> */
%assign u = LibBlockInputSignal(0, "", "", 0)
%assign y = LibBlockOutputSignal(0, "", "", 0)
%% PROVIDE THE CALLING STATEMENT FOR "doubleIt"
%<y> = doubleIt( %<u> );
%endfunction %% Outputs
See Real-Time Workshop Target Language Compiler for more information on writing TLC files.

Using the S-Function Builder to Incorporate Legacy Code

The S-Function Builder automates the creation of S-functions and TLC files that incorporate legacy code. For this example, in addition to you need the header file
doubleIt.h that declares the doubleIt.c function
format, as follows:
extern real_T doubleIt(real_T in1);
The S -Function Builder block in sfcndemo_choosing_sfun.mdl shows how to configure the block dialog to call the legacy function
doubleIt.c.Inthe
S-Function Builder block dialog:
The S-function name field in the Parameters pane defines the name
builder_wrapsfcn for the generated S-function.
doubleIt.c,
2-17
2 Selecting an S-Function Implementation
The Data Properties pane names the input and output ports as in1 and
out1,respectively.
The Libraries pane provides the interface to the legacy code.
- The Library/Object/Source files field contains the source file name
doubleIt.c.
- The Includes field contains the following line to include the header file
that declares the legacy function:
#include <doubleIt.h>
The Outputs pane calls the legacy function with the lines:
/* Call function that multiplies the input by 2 */
The Build Info pane selects the Generate wrapper TLC option.
When you click Build, the S-Function Builder generates three files.
*out1 = doubleIt(*in1);
2-18
File Name
builder_wrapsfcn.c
builder_wrapsfcn_wrapper.c
Description
The main S-function.
A wrapper file containing separate functions for the code entered in the Outputs, Continuous Derivatives, and Discrete Updates panes of the S-Function Builder.
builder_wrapsfcn.tlc
The S-function’s TLC file.
The builder_wrapsfcn.c file follows a standard format:
The file begins with a set of
#define statements that incorporate the
information from the S-Function Builder. For example, the following lines define the first input port:
#define NUM_INPUTS 1
/* Input Port 0 */
#define IN_PORT_0_NAME in1
Example Using S-Functio ns to Incorporate Legacy C Code
#define INPUT_0_WIDTH 1
#define INPUT_DIMS_0_COL 1
#define INPUT_0_DTYPE real_T
#define INPUT_0_COMPLEX COMPLEX_NO
#define IN_0_FRAME_BASED FRAME_NO
#define IN_0_DIMS 1-D
#define INPUT_0_FEEDTHROUGH 1
Next, the file declares all the wrapper functions found in the
builder_wrapsfcn_wrapper.c file. This example requires only a wrapper
function for the Outputs code.
extern void builder_wrapsfcn_Outputs_wrapper(const real_T *in1,
real_T *out1);
Following these definitions and declarations, the file contains the
S-function methods, such as
mdlInitializeSizes, that initialize the
S-function’s input ports, output ports, and parameters. See “Process View” on page 4-77 for a list of methods that are called during the S-function initialization phase.
The file’s
mdlOutputs method calls the builder_wrapsfcn_wrapper.c
function. T he method uses the input and output nam es in1 and out1,as defined in the Data Properties pane, when calling the wrapper function. For example:
/* Function: mdlOutputs =============================================
*
*/
static void mdlOutputs(SimStruct *S, int_T tid)
{
const real_T *in1 = (const real_T*) ssGetInputPortSignal(S,0);
real_T *out1 = (real_T *)ssGetOutputPortRealSignal(S,0);
builder_wrapsfcn_Outputs_wrapper(in1, out1);
}
The file builder_wrapsfcn.c concludes with the required mdlTerminate
method.
The w rapper function
builder_wrapsfcn_wrapper.c has three parts:
2-19
2 Selecting an S-Function Implementation
The Include Files section includes the doubleIt.h file, along with the
standard S-function header files:
/*
* Include Files
*
*/
#if defined(MATLAB_MEX_FILE)
#include "tmwtypes.h"
#include "simstruc_types.h"
#else
#include "rtwtypes.h"
#endif
/* %%%-SFUNWIZ_wrapper_includes_Changes_BEGIN --- EDIT HERE TO _END */
#include <math.h>
#include <doubleIt.h>
/* %%%-SFUNWIZ_wrapper_includes_Changes_END --- EDIT HERE TO _BEGIN */
The External References section contains information from the External
reference declarations field on the Libraries pane. This example does
not use this section.
2-20
The
Output functions section declares the function
builder_wrapfcn_Outputs_wrapper, which contains the code
entered in the S-Function Builder block dialog’s Outputs pane:
/*
* Output functions
*
*/
void builder_wrapfcn_Outputs_wrapper(const real_T *in1,
real_T *out1)
{
/* %%%-SFUNWIZ_wrapper_Outputs_Changes_BEGIN --- EDIT HERE TO _END */
/* Call function that multiplies the input by 2 */
*out1 = doubleIt(*in1);
/* %%%-SFUNWIZ_wrapper_Outputs_Changes_END --- EDIT HERE TO _BEGIN */
}
Example Using S-Functio ns to Incorporate Legacy C Code
Note Compared to a handwritten S-function, the S-Function Builder places the call to the legacy C function down an additional level through the wrapper file
builder_wrapsfcn_wrapper.c.
The TLC file builder_wrapsfcn.tlc generated by the S-Function Builder is similar to the previous handwritten version. The file declares the legacy function in
%implements builder_wrapsfcn "C"
%% Function: BlockTypeSetup ====================================
%%
%% Purpose:
%% Set up external references for wrapper functions in the
%% generated code.
%%
%function BlockTypeSetup(block, system) Output
%openfile externs
BlockTypeSetup and calls it in the Outputs method.
extern void builder_wrapsfcn_Outputs_wrapper(const real_T *in1,
real_T *out1);
%closefile externs
%<LibCacheExtern(externs)>
%%
%endfunction
%% Function: Outputs ===========================================
%%
%% Purpose:
%% Code generation rules for mdlOutputs function.
%%
%function Outputs(block, system) Output
/* S-Function "builder_wrapsfcn_wrapper" Block: %<Name> */
%assign pu0 = LibBlockInputSignalAddr(0, "", "", 0)
%assign py0 = LibBlockOutputSignalAddr(0, "", "", 0)
%assign py_width = LibBlockOutputSignalWidth(0)
%assign pu_width = LibBlockInputSignalWidth(0)
builder_wrapsfcn_Outputs_wrapper(%<pu0>, %<py0> );
2-21
2 Selecting an S-Function Implementation
%%
%endfunction

Using the Legacy Code Tool to Incorporate Legacy Code

The section “Exam ple of Integrating Existing C Functions into Simulink ModelswiththeLegacyCodeTool”onpage4-58in“WritingS-Functions in C” shows how to use the Legacy Code Tool to create an S-function that incorporates example, copy the file that the the script by typing script creates and compiles the S-function the TLC file
doubleIt.c and doubleIt.h files are in your working folder then run
% Create the data structure
def = legacy_code('initialize');
doubleIt.c. For a script that performs the steps in that
lct_wrapsfcn.m to your working folder. Make sure
lct_wrapsfcn at the MATLAB command prompt. The
legacy_wrapsfcn.c and create s
legacy_wrapsfcn.tlc via the following commands.
2-22
% Populate the data struture
def.SourceFiles = {'doubleIt.c'};
def.HeaderFiles = {'doubleIt.h'};
def.SFunctionName = 'legacy_wrapsfcn';
def.OutputFcnSpec = 'double y1 = doubleIt(double u1)';
def.SampleTime = [-1,0];
% Generate the S-function
legacy_code('sfcn_cmex_generate', def);
% Compile the MEX-file
legacy_code('compile', def);
% Generate a TLC-file
legacy_code('sfcn_tlc_generate', def);
The S-function legacy_wrapsfcn.c generated by the Legacy Code Tool begins by including the directly calls the
static void mdlOutputs(SimStruct *S, int_T tid)
doubleIt.h header file. The mdlOutputs method then
doubleIt.c function, as follows:
Example Using S-Functio ns to Incorporate Legacy C Code
{
/*
* Get access to Parameter/Input/Output/DWork/size information
*/
real_T *u1 = (real_T *) ssGetInputPortSignal(S, 0);
real_T *y1 = (real_T *) ssGetOutputPortSignal(S, 0);
/*
* Call the legacy code function
*/
*y1 = doubleIt( *u1);
}
The S-function generated by the Legacy Code Tool differs from the S-function generated by the S-Function Builder as follows:
The S-function generated by the S-Function Builder calls the legacy function
doubleIt.c through the wrapper function builder_wrapsfcn_wrapper.c.
The S-function generated by the Legacy Code Tool directly calls
doubleIt.c
from its mdlOutputs method.
The S-Function Builder uses the input and output names entered into
the Data Properties pane, allowing you to customize these names in the S-function. The Legacy Code Tool uses the default names
y and u for the
outputs and inputs, respectively. You cannot specify customized names to use in the generated S-function when using the Legacy Code Tool.
The S-Function Builder and Legacy Code Tool both specify an inherited
sample time, by default. However, the S-Function Builder uses an offset time of
0.0 while the Legacy Code Tool specifies that the offset time is
fixed in minor time steps.
The TLC file
BlockInstanceSetup and BlockOutputSignal functions. The TLC file also
contains a
doubleIt.c and an Outputs function to tell the Real-Time Workshop code
generator how to inline the call to
%% Function: BlockTypeSetup ===============================================
%%
%function BlockTypeSetup(block, system) void
legacy_wrapsfcn.tlc supports expression folding by defining
BlockTypeSetup function to declare a function prototype for
doubleIt.c.:
2-23
2 Selecting an S-Function Implementation
%%
%% The Target Language must be C
%if ::GenCPP==1
%<LibReportFatalError("This S-Function generated by the Legacy Code Tool
%endif
%<LibAddToCommonIncludes("doubleIt.h")>
%<LibAddToModelSources("doubleIt")>
%%
%endfunction
%% Function: BlockInstanceSetup ===========================================
%%
%function BlockInstanceSetup(block, system) void
%%
%<LibBlockSetIsExpressionCompliant(block)>
%%
%endfunction
must be only used with the C Target Language")>
2-24
%% Function: Outputs ======================================================
%%
%function Outputs(block, system) Output
%%
%if !LibBlockOutputSignalIsExpr(0)
%assign u1_val = LibBlockInputSignal(0, "", "", 0)
%assign y1_val = LibBlockOutputSignal(0, "", "", 0)
%%
%<y1_val = doubleIt( %<u1_val>);
%endif
%%
%endfunction
%% Function: BlockOutputSignal ============================================
%%
%function BlockOutputSignal(block,system,portIdx,ucv,lcv,idx,retType) void
%%
%assign u1_val = LibBlockInputSignal(0, "", "", 0)
%assign y1_val = LibBlockOutputSignal(0, "", "", 0)
%%
%switch retType
Example Using S-Functio ns to Incorporate Legacy C Code
%case "Signal"
%if portIdx == 0
%return "doubleIt( %<u1_val>)"
%else
%assign errTxt = "Block output port index not supported: %<portIdx>"
%endif
%default
%assign errTxt = "Unsupported return type: %<retType>"
%<LibBlockReportError(block,errTxt)>
%endswitch
2-25
2 Selecting an S-Function Implementation
2-26

Writing S-Functions in M

“Introduction” on page 3-2
“Writing Level-2 M-File S-Functions” on page 3-4
“Maintaining Level-1 M-File S-Functions” on page 3-14
3
3 Writing S-Functions in M

Introduction

You can create custom blocks whose properties and behaviors are defined by M-file functions called M-file S-functions. The Level-2 M-file S-function application programming interface (API) allows you to create blocks that have many of the features and capabilities of Simulink built-in blocks, including:
Multiple input and output ports
1-D, 2-D, and n-D input and output signals
All data types supported by the Simulink software
Real or complex signals
Frame-bas ed signals
Multiple sample rates
User-defined data and work vectors
Tunable and run-time param eters
3-2
Note Level-2 M-file S-functions do not support zero-crossing detection.
For information on how to write a Level-2 M-file S-functions, see “Writing Level-2 M-File S-Functions” on page 3-4.
You can generate code for Level-2 M-file S-functions if they are inlined. See “Inlining S-Functions” in the Real-Time Workshop Target Language Compiler documentation for more information.
Introduction
Note This version of the Simulink software also supports a predecessor API known as the Level-1 M-file S-function. This e nsures that you can simulate models developed with earlier releases that use Level-1 M-file S-functions in their S-Function blocks (see “Maintaining Level-1 M-File S-Functions” on page 3-14). Level-1 M-file S-functions support a much smaller subset of the S-function API then Level-2 M-file S-functions, and their features are limited compared to built-in blocks. Use the Level-2 API, not the Level-1 API, to develop new M-file S-functions.
3-3
3 Writing S-Functions in M

Writing Level-2 M-File S-Functions

In this section...
“About Level-2 M-File S-Functions” on page 3-4
“About Run-Time Objects” on page 3-5
“Level-2 M -File S-Function Template” on page 3-5
“Level-2 M-File S-Function Callback M eth ods” on page 3-6
“Using the setup Method” on page 3-8
“Example of Writing a Level-2 M-Fil e S-Function” on page 3-8
“Instantiating a Level-2 M-File S-Function” on page 3-12
“Operations for Variable-Size Signals” on page 3-12
“Generating Code from a Level-2 M-File S-Function” on page 3-13
“M-File S-Function Demos” on page 3-13
3-4

About L evel-2 M-File S-Functions

The Level-2 M-file S-function AP I allows you to use the MATLAB M language to create custom blocks with multiple input and output ports and capable of handling any type of signal produced by a Simulink model, including matrix and frame signals of any data type. The Level-2 M-file S-function API corresponds closely to the API for creating C MEX-file S-functions. Much of the documentation for creating C MEX-file S-functions (see Chapter 4, “Writing S-Functions in C” and Chapter 8 , “Implementing Block Features”) applies also to Level-2 M-file S-functions. To avoid duplication, this section focuses on providing information that is specific to writing Level-2 M-file S-functions.
A Level-2 M-file S-function is an M-file that defines the properties and behavior of an instance of a Level-2 M-File S-Function block that references the M-file in a Simulink model. The M-file itself comprises a set of callback methods (see “Level-2 M-File S-Function Callback Methods” on page 3-6) that the Simulink engine invokes when updating or simulating the model. The callback methods perform the actual work of initializing and computing the outputs of the block defined by the S-function.
Writing Level-2 M-File S-Functions
To facilitate these tasks, the engine passes a run-time object to the callback methodsasanargument. Therun-timeobject effectively serves as an M proxy for the S-Function block, allowing the callback methods to set and access the block properties during simulation or model updating.

About Run-Time Objects

When the Simulink engine invokes a Level-2 M-file S-function callback method, it passes an instance of the the m ethod as an argument. This instan ce, known as the run-time object for the S-Function block, serves the same purpose for Level-2 M-file S-function callback methods as the callback methods. The object enables the method to provide and obtain information about various elements of the block ports, parameters, states, and work vectors. The method does this by getting or setting properties or invoking methods of the block run-time object. See the documentation for the
Simulink.MSFcnRunTimeBlock class for information on getting and setting
run-time object properties and invoking run-time object methods.
SimStruct structure serves for C MEX-file S-function
Simulink.MSFcnRunTimeBlock class to
Run-time objects do not support MATLAB sparse matrices. For example, if the variable S-function produces an error:
block.Outport(1).Data = speye(10);
where the speye command forms a sparse identity matrix.
Note Other M-file programs besides M-file S-functions can use run-time objects to obtain information about an M-file S-function in a model that is simulating. See “Accessing Block Data During Simulation” in Using Simulink for more information.
block is a run-time object, the following line in a Level-2 M-file

Level-2 M-File S-Function Template

Use the basic Level-2 M-file S-function template
matlabroot/toolbox/simulink/blocks/msfuntmpl_basic.m
3-5
3 Writing S-Functions in M
to get a head start on creating a new Level-2 M-file S-function. The template contains skeleton implementation of the required callback methods defined by the Level-2 M-File S-function API. To write a more complicated S-function, use the annotated template
matlabroot/toolbox/simulink/blocks/msfuntmpl.m
To create an M-file S-function, make a copy of the template and edit the copy as necessary to reflect the desired behavior of the S-function you are creating. The following two sections describe the contents of the M-file template. The section “Example of Writing a Level-2 M-File S-Function” on page 3-8 describes how to write a Level-2 M-file S-function that models a unit delay.

Level-2 M-File S-Function Callback Methods

The Level-2 M-file S-function API defines the signatures and general purposes of the callback methods that constitute a Level-2 M-file S-function. The S-function itself provides the implementations of these callbac k methods. The implementations in turn determine the block attributes (e.g., ports, parameters, and states) and behavior (e.g., the block outputs as a function of time and the block inputs, states, and parameters). By creating an S-function with an appropriate set of callback methods, you can define a block type that meets the specific requirements of your application.
3-6
A Lev el-2 M-file S-function must include the following callback methods:
A
setup function to initialize the basic S-function characteristics
Outputs function to calculate the S-function outputs
An
Your S-function can contain other methods, depending on the requirements of the block that the S-function defines. The methods defined by the Level-2 M-file S-function API generally correspond to similarly named methods defined by the C M EX-file S-function API. For information on when these methods are called during simulation, see “Process View” on page 4-77 in “How the Simulink Engine Interacts with C S-Functions” on page 4-77. For instructions on how to implement each callback method, see Chapter 9, “S-Function Callback Methods — Alphabetical List”.
The following table lists all the Level-2 M-file S-function callback methods and their C MEX-file counterparts.
Writing Level-2 M-File S-Functions
Level-2 M-File Method Equiv alent C MEX-File M ethod
setup (see “Using the setup
mdlInitializeSizes
Method” on page 3-8)
CheckParameters mdlCheckParameters
Derivatives mdlDerivatives
Disable mdlDisable
Enable mdlEnable
InitializeCondition mdlInitializeConditions
Outputs mdlOutputs
PostPropagationSetup mdlSetWorkWidths
ProcessParameters mdlProcessParameters
Projection mdlProjection
SetInputPortComplexSignal mdlSetInputPortComplexSignal
SetInputPortDataType mdlSetInputPortDataType
SetInputPortDimensions mdlSetInputPortDimensionInfo
SetInputPortDimensionsModeFcn mdlSetInputPortDimensionsModeFcn
SetInputPortSampleTime mdlSetInputPortSampleTime
SetInputPortSamplingMode mdlSetInputPortFrameData
SetOutputPortComplexSignal mdlSetOutputPortComplexSignal
SetOutputPortDataType mdlSetOutputPortDataType
SetOutputPortDimensions mdlSetOutputPortDimensionInfo
SetOutputPortSampleTime mdlSetOutputPortSampleTime
SimStatusChange mdlSimStatusChange
Start mdlStart
Terminate mdlTerminate
Update mdlUpdate
WriteRTW mdlRTW
3-7
3 Writing S-Functions in M
Using the setup M
tup
The body of the se the instance of t this respect, t
mdlInitialize
S-functions.
Initializing
Setting attr
times for the
Specifying
Using Simul
Setting the
Registeri
local func of the S-F for
Simul
RegBlock
Example
The foll When ap
matlab
used in variab
owing steps illustrate how to write a simple Level-2 M-file S-function.
plicable, the steps include examples from the S-function demo
root/toolbox/simulink/simdemos/simfeatures/msfcn_unit_delay.m
the model
le name
he corresponding Level-2 M-File S-F unction block. In
he
SampleTimes
The
the number of input and output ports of the block.
ibutes such as dimensions, data types, complexity, and sample
se ports.
the block sample time. See “How to Specify the Sample Time” in
ink for more information on how to specify valid sample times.
number of S-function dialog parameters.
ng S-function callback methods by passing the handles of
tions in the M-file S-function to the
unction block’s run-time object. See the documentation
ink.MSFcnRunTimeBlock Method
of Writing a Level-2 M-File S-Function
block for the S-function run-time object.
method in a Level-2 M-file S-function initialize s
setup method is similar to the mdlInitializeSizes and
setup method performs the following tasks:
method.
msfcndemo_sfundsc2.mdl.Alllinesofcodeusethe
ethod
callback methods implemented by C MEX
RegBlockMethod method
for information on using the
3-8
1 Copy t
worki the f
2 Modify the setup method to initialize the S-function’s attributes. For this
he Level-2 M-file S-function tem pl ate
ngfolder.Ifyouchangethefilenamewhenyoucopythefile,change
unctionnameinthe
function line to the same name.
msfuntmpl_basic.m to your
example:
Set the run-time object’s
to
1 to initialize one input port and one output port.
Invoke the run-time object’s
SetPreCompOutPortInfoToDynamic methods to indicate that the
NumInputPorts and NumOutputPorts properties
SetPreCompInpPortInfoToDynamic and
Writing Level-2 M-File S-Functions
input and output ports inherit their compiled properties (dimensions, data type, complexity, and sampling mode) from the model.
Set the
DirectFeedthrough property of the run-time object’s InputPort
to false to indicate the input port does not have direct feedthrough. Retain the default values for all other input and output port properties thataresetinyourcopyofthetemplatefile. Thevaluessetforthe
Dimensions, DatatypeID,andComplexity properties override the
values inherited using the
SetPreCompOutPortInfoToDynamic methods.
Set the run-time object’s
SetPreCompInpPortInfoToDynamic and
NumDialogPrms property to 1 to initialize one
S-function dialog parameter.
Specify that the S-function has an inherited sample time by setting the
valueoftheruntimeobject’s
Call the run-time object’s
SampleTimes property to [-1 0].
RegBlockMethod method to register the
following four callback methods used in this S-function.
PostPropagationSetup
InitializeConditions
Outputs
Update
Remove any other registered callback methods from your copy of the template file. In the calls to
RegBlockMethod, the first input argu m en t is
the name of the S-function API method and the second input argument is the function handle to the associated local function in the M-file S-function.
The following
setup method from msfcn_unit_delay.m performs the
previous list of steps:
function setup(block)
%% Register a single dialog parameter block.NumDialogPrms = 1;
%% Register number of input and output ports block.NumInputPorts = 1; block.NumOutputPorts = 1;
3-9
3 Writing S-Functions in M
%% Setup functional port properties to dynamically %% inherited. block.SetPreCompInpPortInfoToDynamic; block.SetPreCompOutPortInfoToDynamic;
%% Hard-code certain port properties block.InputPort(1).Dimensions = 1; block.InputPort(1).DirectFeedthrough = false;
block.OutputPort(1).Dimensions = 1;
%% Set block sample time to inherited block.SampleTimes = [-1 0];
%% Register methods block.RegBlockMethod('PostPropagationSetup',@DoPostPropSetup); block.RegBlockMethod('InitializeConditions',@InitConditions); block.RegBlockMethod('Outputs', @Output); block.RegBlockMethod('Update', @Update);
3-10
If your S-function needs continuous states, initialize the number of continuous states in the
NumContStates property. Do not initialize discrete states in the setup
setup method using the run-time object’s
method.
3 Initialize the discrete states in the PostPropagationSetup method. A
Level-2 M-file S-function stores discrete state information in a DWork vector. The default
PostPropagationSetup method in the templa te file
suffices for this example.
The following named
DoPostPropSetup, initializes one DWork vector with the name x0.
function DoPostPropSetup(block)
%% Setup Dwork block.NumDworks = 1; block.Dwork(1).Name = 'x0'; block.Dwork(1).Dimensions = 1; block.Dwork(1).DatatypeID = 0; block.Dwork(1).Complexity = 'Real';
PostPropagationSetup method from msfcn_unit_delay.m,
Writing Level-2 M-File S-Functions
block.Dwork(1).UsedAsDiscState = true;
If your S-function uses additional DWork vectors, initialize them in the
PostPropagationSetup method, as well (see “Using DWork Vectors in
Level-2 M-File S-Functions” on page 7-12).
4 Initialize the values of discrete and continuous states or other DWork
vectors in the
Start callback method f or values that are initialized once at the beginning
of the simulation. Use the
InitializeConditions or Start callback methods. Use the
InitializeConditions method for values
that need to be reinitialized whenever an enabled subsystem containing the S-function is reenabled.
For this exa discrete st parameter.
msfcn_uni
function InitConditions(block)
%% Initialize Dwork block.Dwork(1).Data = block.DialogPrm(1).Data;
mple, use the
ate’s initial condition to the value of the S-function’s dialog
For example, the
t_delay.m
InitializeConditions method to set the
InitializeConditions method in
is:
For S-functions w ith continuous states, use the ContStates run-time object method to initialize the continuous state date. For example:
block.ContStates.Data(1) = 1.0;
5 Calculate the S-function’s outputs in the Outputs callback method. For
this example, set the output to the current value of the discrete state stored in the DWork vector.
The
Outputs method in msfcn_unit_delay.m is:
function Output(block)
block.OutputPort(1).Data = block.Dwork(1).Data;
6 ForanS-functionwithcontinuousstates, calculate the state derivatives in
the
Derivatives callback method. Run-time objects store derivative data
in their
Derivatives property. For example, the following line sets the
first state derivative equal to the value of the first input signal.
3-11
3 Writing S-Functions in M
block.Derivatives(1).Data = block.InputPort(1).Data;
This example does not use continuous states and, therefore, does not implement the
7 Update any discrete states in the Update callback method. For this
Derivatives callback method.
example, set the value of the discrete state to the current value of the first input signal.
The
Update method in msfcn_unit_delay.m is:
function Update(block)
block.Dwork(1).Data = block.InputPort(1).Data;
8 Perform any cleanup, such as clearing variables or memory, in the
Terminate method. Unlike C MEX S-functions, Level-2 M-file S-function
are not required to have a
Terminate method.
For information on additional callback methods, see “Level-2 M-File S-Function Callback Methods” on page 3-6. For a list of run-time object properties, see the reference page for parent class
Simulink.RunTimeBlock.
Simulink.MSFcnRunTimeBlock and the
3-12

Instantiating a Level-2 M-File S-Function

To use a Level-2 M-file S-function in a model, copy an instance of the Level-2 M-File S-Function block into the model. Open the Block Parameters dialog boxfortheblockandenterthenameoftheM-filethatimplementsyour S-function into the M-file name field. If your S-function uses any additional parameters, enter the parameter values as a comma-separated list in the Block Parameters dialog box Parameters field.

Operations for Variable-Size Signals

Following are modifications to the Level-2 M-File S-functions template (
msfuntmpl_basic.m) and additional operations that allow you to use
variable-size signals.
function setup(block)
% Register the properties of the output port
Writing Level-2 M-File S-Functions
d
block.OutputPort(1).DimensionsMode = 'Variable';
block.RegBlockMethod('SetInputPortDimensionsMode', @SetInputDimsMode);
function DoPostPropSetup(block)
%Register dependency rules to update current output size of output port a depending on %input ports b an
block.AddOutputDimsDependencyRules(a, [b c], @setOutputVarDims);
%Configure output port b to have the same dimensions as input port a
block.InputPortSameDimsAsOutputPort(a,b);
%Configure DWork a to have its size reset when input size changes.
block.DWorkRequireResetForSignalSize(a,true);
function SetInputDimsMode(block, port, dm)
% Set dimension mode
block.InputPort(port).DimensionsMode = dm;
block.OutputPort(port).DimensionsMode = dm;
function setOutputVarDims(block, opIdx, inputIdx)
% Set current (run-time) dimensions of the output
outDimsAfterReset = block.InputPort(inputIdx(1)).CurrentDimensions;
block.OutputPort(opIdx).CurrentDimensions = outDimsAfterReset;

Generating Code from a Level-2 M-File S-Function

Generating code for a model containing a Level-2 M-file S-function requires that you provide a corresponding Target Language Compiler (TLC) file. You do not need a TLC file to accelerate a model containing a Level-2 M-file S-function. The Simulink Accelerator software runs Level-2 M-file S-functions in interpreted mode. See “Inlining MATLAB File S-Functions” in the R eal-Time Workshop User’s Guide for more information on writing TLC files for M-file S-functions.

M-File S-Function Demos

The Lev el-2 M-file S-function demos provide a set of self-documenting models that illustrate the u se of Level-2 M-file S-functions. Enter MATLAB command prompt to view the demos.
sfundemos at the
3-13
3 Writing S-Functions in M

Maintaining Level-1 M-File S-Functions

In this section...
“About th e Maintenance of Level-1 M-File S-Functions” on page 3-14
“Level-1 M-File S-Function Arguments” on page 3-15
“Level-1 M-File S-Function Outputs” on page 3-16
“Defining S-Function Block Characteristics” on page 3-17
“Processing S-Function Parameters” on p age 3-18
“Converting L eve l-1 M-File S-Functions to Level-2” on page 3-18

About the Maintenance of Level-1 M-File S-Functions

Note The information provided in this section is intended only for use in
maintaining existing Level-1 M-file S-functions. Use the more capable Level-2 API to develop new M-file S-f unctions (see “Writing Level-2 M-File S-Functions” on page 3-4). Level-1 M-file S-functions support a much smaller subset of the S-function API then Level-2 M-file S-functions, and their features are limited compared to built-in blocks.
3-14
A Level-1 M-file S-function is a MATLAB function of the following form
[sys,x0,str,ts]=f(t,x,u,flag,p1,p2,...)
where f is the name of the S-function. During simulation of a model, the Simulink engine repeatedly invokes the task (or tasks) to be performed for a particular invocation. The S-function performs the task and returns the results in an output vector.
A template i mplementation of a Level-1 M-file S-function, resides in of a top-level function and a set of skeleton subfunctions, called S-function callback methods, each of which corresponds to a particular value of top-level function invokes the subfunction indicated by perform the actual tasks required of the S-function during simulation.
matlabroot/toolbox/simulink/blocks. The template consists
f,usingtheflag argument to indicate
sfuntmpl.m,
flag.The
flag. The subfunctions
Maintaining Level-1 M-File S-Functions
Level-1 M-File S
The Simulink eng
-Function Arguments
ine passes the following arguments to a Level-1 M -file
S-function:
t
x
u
flag
Current time
State vector
Input vector
Integer value that indicates the task to be performed by the S-function
The following table describes the values that flag can assume and lists the corresponding Level-2 M-file S-function method for each value.

Flag Argument

Level-1 Flag Level-2 Callback Method Description
0
setup
Defines basic S-Function block characteristics, including sample times, initial conditions of continuous and discrete states, and the
sizes array
(see “Defining S-Function Block Characteristics” on page 3-17 for a description of the
sizes array).
1 mdlDerivatives
Calculates the d erivativ es of the continuous state variables.
2
mdlUpdate
Updates discrete states, sample times, and major time step requirements.
3
mdlOutputs
Calculates the outputs of the S-function.
3-15
3 Writing S-Functions in M
Flag Argument (Continued)
Level-1 Flag Level-2 Callback Method Description
4
mdlOutputs method updates the
run-time object
NextTimeHit
property
Calculates the time of the next hit in absolute time. This routine is used only when you specify a variable discrete-time sample time in the
9
mdlTerminate
Performs any necessary
setup method.
end-of-simulation tasks.

Level-1 M-File S-Function Outputs

A Level-1 M-file S-function returns an output vector containing the following elements:
3-16
sys, a generic return argument. The values returned depend on the flag
value. Fo r example, for flag = 3, sys contains the S-function outputs.
x0, the initial state values (an empty vector if the r e are no states in the
system).
str, reserved for future use. Level-1 M-file S-functions must set this to
the empty matrix,
ts, a two-column matrix containing thesampletimesandoffsetsofthe
x0 is ignored, except when flag = 0.
[].
block(see“HowtoSpecifytheSampleTime”inUsing Simulink for information on how to specify a sample times and offsets).
For example, if you want your S-function to run at every time step (continuous sample time), set
ts to [0 0]. If you want your S-function
to run at the same rate as the block to which it is connected (inherited sample time), set (discrete sample time) starting at time, set
ts to [0.25 0.1].
ts to [-1 0]. If you want it to run every 0.25 seconds
0.1 seconds after the simulation start
You can create S-functions that do multiple tasks, e ach at a different sample rate (i.e., a m ultirate S-function). In this case,
ts should specify
all the sample rates used by your S-function in ascending order by sample
Maintaining Level-1 M-File S-Functions
time. For example, suppose your S-function performs one task every 0.25 second starting from the simulation start time and another task every 1 second starting 0. 1 second after the sim u l ation start time. In this case, your S-function should set the Simulink engine to execute the S -function at the following times: [
0.1 0.25 0.5 0.75 1 1.1 ...]
ts equal to [.25 0; 1.0 .1].Thiswillcause
0
. Your S-function must decide at every
sample time which task to perform at that sample time.
You can also create an S-function that performs some tasks continuously (i.e., at every time step) and others at discrete intervals.

Defining S-Function Block Characteristics

For the Simulink engine to recognize a Level-1 M-file S-function, you must provide it with specific information about the S-function. This information includes the number of inputs, outputs, states, and other block characteristics.
To provide this information, call the
simsizes function at the beginning of
the S-function.
sizes = simsizes;
This function returns an uninitialized sizes structure. You must load the
sizes structure with information about the S-function. The table below lists
the fields of the
sizes structure and describes the information contained
in each field.

Fields in the sizes Structure

Field Name Description
sizes.NumContStates
sizes.NumDiscStates
sizes.NumOutputs
sizes.NumInputs
sizes.DirFeedthrough
sizes.NumSampleTimes
Number of continuous states
Number of discrete states
Number of outputs
Number of inputs
Flag for direct feedthrough
Number of sample times
After you initialize the sizes structure, call simsizes again:
3-17
3 Writing S-Functions in M
sys = simsizes(sizes);
This passes the information in the sizes structure to sys,avectorthatholds the information for use by the Simulink engine.

Processing S-Function Parameters

When invoking a Level-1 M-file S-function, the Simulink engine always passes the standard block parameters, function arguments. The engine can pass additional block-specific parameters specified by the user to the S-function. The user specifies the parameters in the S-function parameters field of the S-Function Block Parameters dialog box (see “Passing Parameters to S-Functions” on page 1-5). If the block dialog specifies addition a l parameters, the engine passes the parameters to the S-function as additional function arguments. The additional arguments follow the standard arguments in the S-function argument list in the order in which the corresponding parameters appear in the block dialog. You can use this block-specific S-function parameter capability to allow the same S-function to implement various processing options. See the example in the matlabroot/toolbox/simulink/blocks folder for an example of an S-function that uses block-specific parameters.
t, x, u,andflag, to the S-function as
limintm.m
3-18

Converting Level-1 M-File S-Functions to Level-2

You can convert Level-1 M-file S-functions to Level-2 M-file S-functions by mapping the code associated with each Level-1 S-function flag to the appropriate Level-2 S-function callback method. See the Flag Arguments table for a mapping of Level-1 flags to Level-2 callback methods. In addition:
Store discrete state information for Level-2 M-file S-functions in DWork
vectors, initialized in the
Access Level-2 M-file S-function dialog parameters using the
run-time object property, instead of passing them into the S-function as function arguments.
For S-functions with variable sample times, update the
run-time object property in the Outputs method to set the next sample time hit for the Level-2 M-file S-function.
PostPropagationSetup method.
DialogPrm
NextTimeHit
Maintaining Level-1 M-File S-Functions
For example, the following table shows how to convert the Level-1 M-file S-function Level-2 M-file S-function template
sfundsc2.m to a Level-2 M-file S-function. The example uses the
msfuntmpl_basic.m as a starting point
when converting the Level-1 M-file S-function. The line numbers in the table corresponds to the lines of code in
sfundsc2.m.
Line #
1
13 ­19
24 ­31
Code in s fundsc2.m Code in Level-2 M-file (sfundsc2_level2.m)
function [sys,x0,str,ts]= ...
sfundsc2(t,x,u,flag)
function sfundsc2(block)
setup(block);
The syntax for the function line changes to accept one input argument
block,whichistheLevel-2
M-File S-Function block’s run-time object. The main body of the Level-2 M-file S-function contains
switch flag,
case 0,
[sys,x0,str,ts] = ...
mdlInitializeSizes;
asinglelinethatcallsthelocal
function setup(block)
The flag value of zero corresponds to calling the
setup method. A Level-2 M-file S-function
does not use a
switch statement to invoke the
callback methods. Instead, the local
setup function.
setup function
registers callback methods that are directly called during simulation.
The setup function registers two local functions
case 2,
sys = mdlUpdate(t,x,u);
case 3,
sys = mdlOutputs(t,x,u);
associated with
block.RegBlockMethod('Outputs' ,@Output);
block.RegBlockMethod('Update' ,@Update);
flag values of 2 and 3.
3-19
3 Writing S-Functions in M
Line #
53 ­66
56
Code in s fundsc2.m Code in Level-2 M-file (sfundsc2_level2.m)
The setup function a l so initializes the attributes of
sizes = simsizes;
sizes.NumContStates = 0;
sizes.NumDiscStates = 1;
sizes.NumOutputs = 1;
sizes.NumInputs = 1;
sizes.DirFeedthrough = 0;
sizes.NumSampleTimes = 1;
sys = simsizes(sizes);
the Level-2 M-file S-fun c tion:
block.NumInputPorts = 1;
block.NumOutputPorts = 1;
block.InputPort(1).Dimensions = 1;
block.InputPort(1).DirectFeedthrough = false;
block.OutputPort(1).Dimensions = 1;
block.NumDialogPrms = 0;
block.SampleTimes = [0.1 0];
Because this S-function has discrete states, the
x0 = 0;
str = [];
ts = [.1 0];
setup method registers the PostPropagationSetup
callback method to initialize a DWork vector and the
InitializeConditions callback method to set
the initial state value.
block.RegBlockMethod('PostPropagationSetup',...
@DoPostPropSetup);
block.RegBlockMethod('InitializeConditions', ...
@InitConditions);
The PostPropagationSetup method initializes the
sizes.NumDiscStates = 1;
DWork vector that stores the single discrete state.
3-20
function DoPostPropSetup(block)
%% Setup Dwork
block.NumDworks = 1;
block.Dwork(1).Name = 'x0';
block.Dwork(1).Dimensions = 1;
block.Dwork(1).DatatypeID = 0;
block.Dwork(1).Complexity = 'Real';
block.Dwork(1).UsedAsDiscState = true;
Maintaining Level-1 M-File S-Functions
Line #
64
77 ­78
88 ­89
Code in s fundsc2.m Code in Level-2 M-file (sfundsc2_level2.m)
The InitializeConditions method initializes the
x0 = 0;
discrete state value.
function InitConditions(block)
%% Initialize Dwork
block.Dwork(1).Data = 0
The Update method calculates the next value of the
function sys = ...
mdlUpdate(t,x,u)
sys = u;
discrete state.
function Update(block)
block.Dwork(1).Data = block.InputPort(1).Data;
The Outputs method calculates the S-function’s
function sys = ...
mdlOutputs(t,x,u)
sys = x;
output.
function Output(block)
block.OutputPort(1).Data = block.Dwork(1).Data;
3-21
3 Writing S-Functions in M
3-22

Writing S-Functions in C

“Introduction” on page 4-2
“Building S-Functions Automatically” on page 4-5
“S-Functi on Builder Dialog Box” on page 4-12
“Example of a Basic C MEX S-Function” on page 4-43
“Templates for C S-Functions” on page 4-50
“Integrating Existing C Functions into Simulink Models with the Legacy
Code Tool” on page 4-55
4
“How the Simulink Engine Interacts with C S-Functions” on p age 4-77
“Writing Callback Methods” on page 4-90
“Using S-Functions in Normal Mode Referenced Models” on page 4-91
“Debugging C MEX S-Functions” on page 4-93
“Converting Level-1 C MEX S-Functions to Level-2” on page 4-102
4 Writing S-Functions in C

Introduction

In this section...
“About Writing C S-Functions” on page 4-2
“Creating C MEX S-Functions” on page 4-3

About Writing C S-Functions

A C MEX S-function must provide information about the function to the Simulink engine during the simulation. As the simulation proceeds, the engine, the ODE solver, and the C M EX S-function interact to perform specific tasks. These tasks include defining initial conditions and block characteristics, and computing derivatives, discrete states, and outputs.
As with M -file S-functions, the Simulink engine interacts with a C MEX S-function by invoking callback methods that the S-function implements. Each method performs a predefined task, such as computing block outputs, required to simulate the block whose functionality the S-function defines. However, the S-function is free to perform the task in each method according to the functionality the S-function implements. For example, the method must compute the block outputs at the current simulation time. However, the S-function can calculate these outputs in any way that is appropriate for the function. This callback-based API allows you to create S-functions, and hence custom blocks, of any desired functionality.
mdlOutputs
4-2
The set of callback methods that C MEX S-functions can implement is larger than that available for M-file S-functions. See Chapter 9, “S-Function Callback Methods — Alphabetical List” for descriptions of the callback methods that a C M EX S-function can implement. C MEX S-functions are required to implement only a small subset of the callback m ethods in the S-function API. If your block does not implement a particular feature, such as matrix signals, you are free to omit the callback methods needed to implement a f eature. This allows you to createsimpleblocksveryquickly.
The general format of a C MEX S-function is shown below:
#define S_FUNCTION_NAME your_sfunction_name_here #define S_FUNCTION_LEVEL 2
#include "simstruc.h"
static void mdlInitializeSizes(SimStruct *S) { }
<additional S-function routines/code>
static void mdlTerminate(SimStruct *S) { } #ifdef MATLAB_MEX_FILE /* Is this file being compiled as a
MEX-file? */ #include "simulink.c" /* MEX-file interface mechanism */ #else #include "cg_sfun.h" /* Code generation registration
function */ #endif
Introduction
mdlInitializeSizes
is the first routine the Simulink engine calls when interacting with the S-function. The engine subsequently invokes other S-function methods (all starting with engine calls
mdlTerminate.
mdl). At the end of a simulation, the

Creating C MEX S-Functions

You can create C MEX S-functions using any of the following approaches:
HandwrittenS-function—YoucanwriteaCMEXS-functionfrom
scratch. (“Example of a Basic C MEX S-Function” on page 4-43 provides a step-by-step example.) See “Templates for C S-Functions” on page 4-50 for a complete skeleto n implementation of a C MEX S-function that you can use as a starting point for creating your own S-functions.
S-Function Builder — This block builds a C MEX S-function from
specifications and c od e fragments that y ou supply using a graphical user interface. This eliminates the need f or you to write S-functions from scratch. See “Building S-Functions Automatically” on page 4-5 for more information about the S-Function Builder.
4-3
4 Writing S-Functions in C
Legacy Code Tool — This utility builds a C MEX S-function from existing
C code and specifications that you supply using MATLAB M-code. See “Integrating Existing C Functions into Simulink Models with the Legacy Code Tool” on page 4-55 for more information about integrating legacy C code into Simulink models.
Each of these approaches involves a tradeoff between the ease of writing an S-function and the features supported by the S-function. Although handwritten S-functions support the widest range of features, they can be difficult to write. The S-Function Builder block s im plifies the task o f writing C MEX S-functions but supports fewer features. The Legacy Code Tool provides the easiest approach to creating C MEX S-functions from existing C code but supports the fewest features. See Chapter 2, “Selecting an S-Function Implementation” for more information on the features and limitations of each of these approaches to writing a C MEX S-function.
In addition to these three approaches, the Real-Time Workshop product provides a method for generating a C MEX S-function from a graphical subsystem. If you are new to writing CMEXS-functions,youcanbuild portions of your application in a Simulink subsystem and use the S-function target to convert it to an S-function. The generated files provides insight on how particular blocks can be implemented w ithin an S-function. See “Creating Component Object L ibraries and Enhancing Simulation Performance” in the Real-Time Workshop User’s Guide for details and limitations on using the S-function target.
4-4

Building S-Functions Automatically

In this section...
“About Building S-Functions Autom atically” on page 4-5
“Deploying the Generated S-Function” on page 4-10
“How the S-Function Builder Builds an S-Function” on page 4-11

About Building S-Functions Automatically

The S-Function Builder is a Simulink block tha t builds an S-function from specifications and C code that you supply . The S-Function Buil der als o serves as a wrapper for the generated S-function in models that use the S-function. This section explains how to use the S-Function Builder to build simple C MEX S-functions.
Note For examples of using the S-Function Builder to build S-functions, see the C-file S-functions subsystem of the S-function demos provided with the Simulink product. To display the demos, enter command line (see “S-Function Examples” on page 1-21 for more information).
Building S-Functions Automatically
sfundemos at the MATLAB
To build an S-function with the S-Function Builder:
1 Set the MATLAB current folder to the folder in which you want to create
the S-function.
Note This folder must be on the MATLAB path.
2 If you wish to connect a bus signal to the Input or Output port of the
S-Function Builder, you must first create a bus object. You perform this task interactively using the Simulink Bus Editor. (For more information, see “Using the Bus Editor”. Alternatively, you can use follows.
a At the MATLAB command line, enter:
Simulink.Bus as
4-5
4 Writing S-Functions in C
a = Simulink.Bus
As a result, the HeaderFile forthebusdefaultstotheemptystring:
a=
Simulink.Bus
Description: ''
HeaderFile: ''
Elements: [0x1 double]
b Ifyouwishtospecifytheheaderfileforthebus,thenattheMATLAB
command line:
a.Headerfile = 'Busdef.h'
If you do not specify a hea de r file, Simulink automatically generates
Sfunctionname_bus.h
4-6
Building S-Functions Automatically
For a demonstration on how to use the S-Function Builder with a bus, see the
S-Function Builder with buses example by entering the following
command at the MATLAB command line:
open_system([matlabroot,'/toolbox/simulink/simdemos/ simfeatures/sfbuilder_bususage.mdl']);
3 Create a new Simulink model.
4 Copy an instance of the S-Function Builder block from the User-Defined
Functions library in the Library Browser into the new model.
4-7
4 Writing S-Functions in C
5 Double-click the block to open the S-Function Builder dialog box (see
“S-Function Builder Dialog Box” on page 4-12).
4-8
Loading...