Matlab S Function Ref
Matlab S Function Ref
7
Writing S-Functions
How to Contact The MathWorks
www.mathworks.com Web
comp.soft-sys.matlab Newsgroup
www.mathworks.com/contact_TS.html Technical Support
suggest@mathworks.com Product enhancement suggestions
bugs@mathworks.com Bug reports
doc@mathworks.com Documentation error reports
service@mathworks.com Order status, license renewals, passcodes
info@mathworks.com Sales, pricing, 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.
Writing S-Functions
COPYRIGHT 19982007 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 MathWorks, 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 the use,
modification, reproduction, release, performance, display, and disclosure of the Program and 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 governments
needs or is inconsistent in any respect with federal procurement law, the government agrees to return the
Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB, Simulink, Stateflow, Handle Graphics, Real-Time Workshop, SimBiology,
SimHydraulics, SimEvents, and xPC TargetBox are registered trademarks and The
MathWorks, the L-shaped membrane logo, Embedded MATLAB, and PolySpace are
trademarks of The MathWorks, Inc.
Other product or brand names are 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 Simulink 3.0 (Release R11)
November 2000 Second printing Revised for Simulink 4.0 (Release R12)
July 2002 Third printing Revised for Simulink 5.0 Release R13)
April 2003 Online only Revised for Simulink 5.1 (Release R13SP1)
April 2004 Online only Revised for Simulink 5.1.1 (Release R13SP1+)
June 2004 Online only Revised for Simulink 6.0 (Release R14)
October 2004 Online only Revised for Simulink 6.1 (Release R14SP1)
March 2005 Online only Revised for Simulink 6.2 (Release R14SP2)
September 2005 Online Only Revised for Simulink 6.3 (Release R14SP3)
March 2006 Online only Revised for Simulink 6.4 (Release 2006a)
September 2006 Online only Revised for Simulink 6.5 (Release 2006b)
March 2007 Online only Revised for Simulink 6.6 (Release 2007a)
September 2007 Online only Revised for Simulink 7.0 (Release 2007b)
Contents
Overview of S-Functions
1
What Is an S-Function? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Using S-Functions in Models . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Passing Parameters to S-Functions . . . . . . . . . . . . . . . . . . . 1-5
When to Use an S-Function . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
How S-Functions Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7
Mathematics of Simulink Blocks . . . . . . . . . . . . . . . . . . . . . 1-7
Simulation Stages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8
S-Function Callback Methods . . . . . . . . . . . . . . . . . . . . . . . 1-9
Implementing S-Functions . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
M-File S-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
MEX-File S-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12
S-Function Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14
Direct Feedthrough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14
Dynamically Sized Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15
Setting Sample Times and Offsets . . . . . . . . . . . . . . . . . . . . 1-16
S-Function Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-20
Overview of Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-20
Level-2 M-File S-Function Examples . . . . . . . . . . . . . . . . . . 1-22
Level-1 M-File S-Function Examples . . . . . . . . . . . . . . . . . . 1-22
C S-Function Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-25
Fortran S-Function Examples . . . . . . . . . . . . . . . . . . . . . . . 1-29
C++ S-Function Examples . . . . . . . . . . . . . . . . . . . . . . . . . . 1-30
Ada S-Function Examples . . . . . . . . . . . . . . . . . . . . . . . . . . 1-30
v
Writing S-Functions in M
2
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Writing Level-2 M-File S-Functions . . . . . . . . . . . . . . . . . . 2-3
About Level-2 M-File S-Functions . . . . . . . . . . . . . . . . . . . . 2-3
Level-2 M-File S-Function API . . . . . . . . . . . . . . . . . . . . . . . 2-4
M-File S-Function Demos . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
S-Function Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
Instantiating a Level-2 M-File S-Function . . . . . . . . . . . . . 2-4
Generating Code from a Level-2 M-File S-Function . . . . . . 2-5
Callback Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
Setup Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
Run-time Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Maintaining Level-1 M-File S-Functions . . . . . . . . . . . . . 2-9
About the Maintenance of Level-1 M-File S-Functions . . . 2-9
S-Function Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
S-Function Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11
Defining S-Function Block Characteristics . . . . . . . . . . . . . 2-12
Processing S-Function Parameters . . . . . . . . . . . . . . . . . . . 2-13
Converting Level-1 M-File S-functions to Level-2 . . . . . . . . 2-13
Writing S-Functions in C
3
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
About Writing C S-Functions . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Creating C MEX S-Functions . . . . . . . . . . . . . . . . . . . . . . . . 3-4
Building S-Functions Automatically . . . . . . . . . . . . . . . . . 3-6
About Building S-Functions Automatically . . . . . . . . . . . . . 3-6
Deploying the Generated S-Function . . . . . . . . . . . . . . . . . . 3-9
How the S-Function Builder Builds an S-Function . . . . . . 3-10
S-Function Builder Dialog Box . . . . . . . . . . . . . . . . . . . . . . 3-11
About S-Function Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11
vi Contents
Parameters/S-Function Name Pane . . . . . . . . . . . . . . . . . . . 3-13
Port/Parameter Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-14
Initialization Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-14
Data Properties Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-16
Input Ports Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-18
Output Ports Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-19
Parameters Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-21
Data Type Attributes Pane . . . . . . . . . . . . . . . . . . . . . . . . . . 3-22
Libraries Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-23
Outputs Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-25
Continuous Derivatives Pane . . . . . . . . . . . . . . . . . . . . . . . . 3-29
Discrete Update Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-31
Build Info Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-33
Example: Modeling a Two-Input/Two-Output System . . . . 3-35
Example of a Basic C MEX S-Function . . . . . . . . . . . . . . . 3-41
Introducing an Example of a Basic C MEX S-Function . . . 3-41
Defines and Includes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-44
Callback Implementations . . . . . . . . . . . . . . . . . . . . . . . . . . 3-44
Simulink/Real-Time Workshop Interface . . . . . . . . . . . . . . 3-46
Building the Timestwo Example . . . . . . . . . . . . . . . . . . . . . 3-46
Templates for C S-Functions . . . . . . . . . . . . . . . . . . . . . . . . 3-48
About the Templates for C S-Functions . . . . . . . . . . . . . . . . 3-48
S-Function Source File Requirements . . . . . . . . . . . . . . . . . 3-48
The SimStruct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-51
Data Types in S-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 3-51
Compiling C S-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-51
Integrating Existing C Functions into Simulink Models
with the Legacy Code Tool . . . . . . . . . . . . . . . . . . . . . . . 3-53
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-53
Example of Integrating Existing C Functions into Simulink
Models with the Legacy Code Tool . . . . . . . . . . . . . . . . . . 3-56
Registering Legacy Code Tool Data Structures . . . . . . . . . . 3-60
Declaring Legacy Code Tool Function Specifications . . . . . 3-62
Generating and Compiling the S-Functions . . . . . . . . . . . . 3-69
Generating a Masked S-Function Block for Calling a
Generated S-Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-70
Forcing Accelerator Mode to Use S-Function TLC Inlining
Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-71
Handling Multiple Registration Files . . . . . . . . . . . . . . . . . 3-71
Deploying Generated S-Functions . . . . . . . . . . . . . . . . . . . . 3-72
vii
Legacy Code Tool Demos . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-72
Legacy Code Tool Limitations . . . . . . . . . . . . . . . . . . . . . . . 3-73
How Simulink Interacts with C S-Functions . . . . . . . . . 3-74
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-74
Process View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-74
Data View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-78
Writing Callback Methods . . . . . . . . . . . . . . . . . . . . . . . . . . 3-82
Using S-Functions in Normal Mode Referenced
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-83
Debugging C MEX S-Functions . . . . . . . . . . . . . . . . . . . . . . 3-85
About Debugging C MEX S-Functions . . . . . . . . . . . . . . . . . 3-85
Debugging C MEX S-Functions Using Microsoft Visual
C/C++ .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-85
Debugging C MEX S-Functions Using UNIX . . . . . . . . . . . 3-86
Converting Level 1 C MEX S-Functions to Level 2 . . . . 3-89
Guidelines for Converting Level 1 C MEX S-Functions to
Level 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-89
Obsolete Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-92
Creating C++ S-Functions
4
Source File Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Making C++ Objects Persistent . . . . . . . . . . . . . . . . . . . . . . 4-6
Building C++ S-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8
viii Contents
Creating Ada S-Functions
5
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
About Simulink and Ada . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Ada Compiler Requirements . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Ada S-Function Source File Format . . . . . . . . . . . . . . . . . 5-4
Ada S-Function Specification . . . . . . . . . . . . . . . . . . . . . . . . 5-4
Ada S-Function Body . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5
Writing Callback Methods in Ada . . . . . . . . . . . . . . . . . . . 5-8
Callbacks Invoked by Simulink . . . . . . . . . . . . . . . . . . . . . . 5-8
Implementing Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10
Omitting Optional Callback Methods . . . . . . . . . . . . . . . . . 5-10
SimStruct Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10
Building an Ada S-Function . . . . . . . . . . . . . . . . . . . . . . . . 5-11
Example of an Ada S-Function . . . . . . . . . . . . . . . . . . . . . . 5-12
Overview of an Example of an Ada S-Function . . . . . . . . . . 5-12
Times_two Package Specification . . . . . . . . . . . . . . . . . . . . . 5-13
Times_two Package Body . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16
mdlInitializeSizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-18
mdlOutputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-18
Building the Times_two Example . . . . . . . . . . . . . . . . . . . . 5-19
Creating Fortran S-Functions
6
Level 1 Versus Level 2 S-Functions . . . . . . . . . . . . . . . . . . 6-2
Creating Level 1 Fortran S-Functions . . . . . . . . . . . . . . . 6-3
Fortran MEX Template File . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Example of a Level 1 Fortran S-Function . . . . . . . . . . . . . . 6-3
Inline Code Generation Example . . . . . . . . . . . . . . . . . . . . . 6-6
ix
Creating Level 2 Fortran S-Functions . . . . . . . . . . . . . . . 6-8
About Creating Level 2 Fortran S-Functions . . . . . . . . . . . 6-8
Template File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8
C/Fortran Interfacing Tips . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8
Constructing the Gateway . . . . . . . . . . . . . . . . . . . . . . . . . . 6-13
Example C MEX S-Function Calling Fortran Code . . . . . . 6-16
Porting Legacy Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-19
Find the States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-19
Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-20
Multiple Instances . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-20
Use Flints if Needed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-20
Considerations for Real Time . . . . . . . . . . . . . . . . . . . . . . . . 6-20
Implementing Block Features
7
Dialog Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
About Dialog Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
Tunable Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4
Run-Time Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7
About Run-Time Parameters . . . . . . . . . . . . . . . . . . . . . . . . 7-7
Creating Run-Time Parameters . . . . . . . . . . . . . . . . . . . . . . 7-8
Updating Run-Time Parameters . . . . . . . . . . . . . . . . . . . . . 7-14
Tuning Runtime Parameters . . . . . . . . . . . . . . . . . . . . . . . . 7-15
Creating Input and Output Ports . . . . . . . . . . . . . . . . . . . . 7-16
Creating Input Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-16
Creating Output Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-20
Scalar Expansion of Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . 7-21
Masked Multiport S-Functions . . . . . . . . . . . . . . . . . . . . . . . 7-23
Custom Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-24
Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-26
About Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-26
Block-Based Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . 7-27
x Contents
Specifying Port-Based Sample Times . . . . . . . . . . . . . . . . . 7-31
Hybrid Block-Based and Port-Based Sample Times . . . . . . 7-36
Multirate S-Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . 7-37
Synchronizing Multirate S-Function Blocks . . . . . . . . . . . . 7-39
Specifying Model Reference Sample Time Inheritance . . . . 7-40
Work Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-42
About Work Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-42
Work Vectors and Zero Crossings . . . . . . . . . . . . . . . . . . . . . 7-44
Example Involving a Pointer Work Vector . . . . . . . . . . . . . . 7-47
Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-49
Function-Call Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . 7-50
Sim Viewing Devices in External Mode . . . . . . . . . . . . . . 7-55
Processing Frame-Based Signals . . . . . . . . . . . . . . . . . . . . 7-56
Handling Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-59
About Handling Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-59
Exception Free Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-60
ssSetErrorStatus Termination Criteria . . . . . . . . . . . . . . . . 7-61
Checking Array Bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-62
S-Function Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-63
About S-Function Examples . . . . . . . . . . . . . . . . . . . . . . . . . 7-63
Continuous States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-63
Discrete States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-70
Continuous and Discrete States . . . . . . . . . . . . . . . . . . . . . . 7-77
Variable Sample Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-84
Array Inputs and Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . 7-90
Zero-Crossing Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-102
Discontinuities in Continuous States . . . . . . . . . . . . . . . . . 7-119
xi
S-Function Callback Methods Alphabetical
List
8
SimStruct Functions By Category
9
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
About SimStruct Functions . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Language Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
The SimStruct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
SimStruct Macros and Functions Listed by Usage . . . . 9-3
Input and Output Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6
Run-Time Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-12
State and Work Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-17
S-Function Options Alphabetical List
10
Examples
A
S-Function Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2
S-Function Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2
S-Function Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2
Writing S-Functions in C . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2
xii Contents
Creating C++ S-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . A-2
Creating Ada S-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . A-3
Creating Fortran S-Functions . . . . . . . . . . . . . . . . . . . . . . . A-3
Index
xiii
xiv Contents
1
Overview of S-Functions
What Is an S-Function? (p. 1-2) Brief overview of S-functions.
Using S-Functions in Models (p. 1-3) How to insert S-functions as blocks
in a model and pass parameters to
them.
How S-Functions Work (p. 1-7) How Simulink invokes S-functions
when simulating a model that
includes them.
Implementing S-Functions (p. 1-11) How to write S-functions.
S-Function Concepts (p. 1-14) Key concepts needed to write certain
types of S-functions.
S-Function Examples (p. 1-20) Examples that illustrate the creation
of various types of S-functions and
S-function features.
1 Overview of S-Functions
What Is an S-Function?
S-functions (system-functions) provide a powerful mechanism for extending
the capabilities of Simulink
, C,
C++, Ada, or Fortran. C, C++, Ada, and Fortran S-functions are compiled as
MEX-files using the mex utility (see Building MEX-Files in the External
Interfaces Users Guide). As with other MEX-files, they are dynamically
linked into MATLAB when needed.
S-functions use a special calling syntax that enables you to interact with
Simulink equation solvers. This interaction is very similar to the interaction
that takes place between the solvers and built-in Simulink blocks. The form
of an S-function is very general and can accommodate continuous, discrete,
and hybrid systems.
S-functions allow you to add your own blocks to Simulink models. You can
create your blocks in MATLAB, C, C++, Fortran, or Ada. By following a set of
simple rules, you can implement your algorithms in an S-function. After you
write your S-function and place its name in an S-Function block (available
in the User-Defined Functions block library), you can customize the user
interface by using masking.
You can use S-functions with Real-Time Workshop
Visual
Fortran 9.0 (formerly known as Compaq Visual Fortran), this example can be
compiled using the following mex commands (each command is on one line).
mex -v -c sfun_atmos_sub.F -f ..\..\bin\win32\mexopts\
intelf90opts.bat
!mex -v -L"%IFORT_COMPILER90%\IA32\LIB" -llibifcoremd
-lifconsol -lifportmd -llibmmd -llibirc sfun_atmos.c
sfun_atmos_sub.obj
On 64-bit Windows machines, using Microsoft Visual C/C++ and Intel
Visual
Fortran 9.0 (formerly known as Compaq Visual Fortran), this example can be
compiled using the following mex commands (each command is on one line).
mex -v -c sfun_atmos_sub.F -f ..\..\bin\win64\mexopts\
6-12
Creating Level 2 Fortran S-Functions
intelf90opts.bat
!mex -v -L"%IFORT_COMPILER90%\EM64T\LIB" -llibifcoremd
-lifconsol -lifportmd -llibmmd -llibirc sfun_atmos.c
sfun_atmos_sub.obj
CFortran
Or you can try using CFortran to create an interface. CFortran is a tool for
automated interface generation between C and Fortran modules, in either
direction. Search the Web for cfortran or visit
http://www-zeus.desy.de/~burow/cfortran/
for downloading.
Obtaining a Fortran Compiler
On Windows, using Visual C/C++ with Fortran is best done with Intel
( , )
*
t
n
is the time at the current time step
R
n
is the residual (difference) between the invariant function
evaluated at X
n
and X
n
*
at the current time step:
R g X t g X t
n n n n n
= ( , ) ( , )
*
Note The value of g X t
n n
( , ) is the same at each time step and is
known by definition.
Given a continuous, differentiable invariant function for the system
that your S-function models, this formula allows your S-functions
mdlProjection method to compute a perturbation
J J J R
n
T
n n
T
n
( )
1
of the solvers numerical solution, X
n
*
, that more closely matches the
ideal solution, X
n
, keeping the S-functions solution from drifting from
the ideal solution as the simulation progresses.
Example
This example illustrates how the perturbation method outlined in the
previous section can keep a models numerical solution from drifting
from the ideal solution as a simulation progresses. Consider the
following model (open):
8-32
mdlProjection
The PredPrey block references an S-function, predprey_noproj.m, that
uses the Lotka-Volterra equations
x ax y
y cy x
=
=
( )
( )
1
1
to model predator-prey population dynamics, where x t ( ) is the
population density of the predators and y t ( ) is the population density
of prey. The ideal solution to the predator-prey ODEs satisfies the
time-invariant function
x e y e d
c cx a ay
=
where a , c , and d are constants. The S-function assumes a = 1, c =
2, and d = 121.85.
The Invariant Residual block in this model computes the residual
between the invariant function evaluated along the systems ideal
trajectory through state space and its simulated trajectory:
R d x e y e
n n
c cx
n
a ay
n n
=
where x
n
and y
n
are the values computed by the models solver for the
predator and prey population densities, respectively, at the current
time step. Ideally, the residual should be zero throughout simulation of
the model, but simulating the model reveals that the residual actually
strays considerably from zero:
8-33
mdlProjection
Now consider the following model (open):
This model is the same as the previous model, except that its
S-function, predprey.m, includes a mdlProjection method that uses
8-34
mdlProjection
the perturbation approach outlined in Perturbing a Systems States
Using a Solution Invariant on page 8-31 to compensate for numerical
drift. As a result, the numerical solution more closely tracks the ideal
solution as the simulation progresses as demonstrated by the residual
signal, which remains near or at zero throughout the simulation:
Languages C, M
8-35
mdlRTW
Purpose Generate code generation data
Required No
C Syntax void mdlRTW(SimStruct *S)
C
Arguments
S
SimStruct representing an S-Function block.
M Syntax WriteRTW(s)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
Description This function is called when Real-Time Workshop is generating the
model.rtw file. In this method, you can call the following functions that
add fields to the model.rtw file:
ssWriteRTWParameters
ssWriteRTWParamSettings
ssWriteRTWWorkVect
ssWriteRTWStr
ssWriteRTWStrParam
ssWriteRTWScalarParam
ssWriteRTWStrVectParam
ssWriteRTWVectParam
ssWriteRTW2dMatParam
ssWriteRTWMxVectParam
8-36
mdlRTW
ssWriteRTWMx2dMatParam
This function must be enclosed in a #if defined(MATLAB_MEX_FILE)
statement.
Languages C, C++, M
See Also ssSetInputPortFrameData, ssSetOutputPortFrameData,
ssSetErrorStatus
8-37
mdlSetDefaultPortComplexSignals
Purpose Set the numeric types (real, complex, or inherited) of ports whose
numeric types cannot be determined from block connectivity
Required No
C Syntax void mdlSetDefaultPortComplexSignals(SimStruct *S)
C
Arguments
S
SimStruct representing an S-Function block.
Description Simulink invokes this method if the block has ports whose numeric
types cannot be determined from connectivity. (This usually happens
when the block is unconnected or is part of a feedback loop.) This
method must set the numeric types of all ports whose numeric types are
not set. This method is only valid for simulation, and must be enclosed
in a #if defined(MATLAB_MEX_FILE) statement.
If the block does not implement this method and at least one port is
known to be complex, Simulink sets the unknown ports to COMPLEX_YES;
otherwise, it sets the unknown ports to COMPLEX_NO.
Languages C
See Also ssSetOutputPortComplexSignal, ssSetInputPortComplexSignal
8-38
mdlSetDefaultPortDataTypes
Purpose Set the data types of ports whose data types cannot be determined from
block connectivity
Required No
C Syntax void mdlSetDefaultPortDataTypes(SimStruct *S)
C
Arguments
S
SimStruct representing an S-Function block.
Description Simulink invokes this method if the block has ports whose data types
cannot be determined from block connectivity. (This usually happens
when the block is unconnected or is part of a feedback loop.) This
method must set the data types of all ports whose data types are not
set. This method is only valid for simulation, and must be enclosed in a
#if defined(MATLAB_MEX_FILE) statement.
If the block does not implement this method and Simulink cannot
determine the data types of any of its ports, Simulink sets the data
types of all the ports to double. If the block does not implement this
method and Simulink cannot determine the data types of some, but not
all, of its ports, Simulink sets the unknown ports to the data type of the
port whose data type has the largest size.
Simulink invokes an error if the mdlSetDefaultPortDataType
method attempts to modify the data type of a port when the data
type was previously specified by mdlSetInputPortDataType or
mdlSetOutputPortDataType. If an S-function has multiple input or
output ports, mdlSetDefaultPortDataType should check if the data
type of a port is still dynamic before attempting to set the type. For
example, the mdlSetDefaultPortDataType uses the following lines to
check if the data type of the second input port is still unknown.
if (ssGetInputPortDataType(S, 1) == DYNAMICALLY_TYPED) {
ssSetInputPortDataType(S, 1, SS_UINT8 );
}
8-39
mdlSetDefaultPortDataTypes
Languages C
See Also ssSetOutputPortDataType, ssSetInputPortDataType
8-40
mdlSetDefaultPortDimensionInfo
Purpose Set the default dimensions of the signals accepted or emitted by an
S-functions ports
Required No
C Syntax void mdlSetDefaultPortDimensionInfo(SimStruct *S)
C
Arguments
S
SimStruct representing an S-Function block.
Description Simulink calls this method during signal dimension propagation
when a model does not supply enough information to determine
the dimensionality of signals that can enter or leave the block
represented by S. This method should set the dimensions of any input
and output ports that are dynamically sized to default values. This
method is only valid for simulation, and must be enclosed in a #if
defined(MATLAB_MEX_FILE) statement.
If the S-function does not implement this method, Simulink tries to
find a set of dimensions that will satisfy the dimension propagation
rules implemented using mdlSetInputPortDimensionInfo and
mdlSetOutputPortDimensionInfo. This process might not be able to
produce a valid set of dimensions for S-functions with special dimension
requirements.
Simulink invokes an error if the mdlSetDefaultPortDimensionInfo
method attempts to modify the dimensions of a port when the dimensions
were previously specified by mdlSetInputPortDimensionInfo or
mdlSetOutputPortDimensionInfo. If an S-function has multiple input
or output ports, mdlSetDefaultPortDimensionInfo should check if the
dimensions of the port are still dynamic before attempting to set the
dimensions. For example, the mdlSetDefaultPortDimensionInfo uses
the following lines to check if the dimensions of the first output port are
still unknown.
if (ssGetOutputPortWidth(S, 0) == DYNAMICALLY_SIZED) {
8-41
mdlSetDefaultPortDimensionInfo
ssSetOutputPortMatrixDimensions(S, 0, 1, 1 );
}
Example See matlabroot/simulink/src/sfun_matadd.c for an example of how
to use this function.
Languages C
See Also ssSetErrorStatus, ssSetOutputPortMatrixDimensions
8-42
mdlSetInputPortComplexSignal
Purpose Set the numeric types (real, complex, or inherited) of the signals
accepted by an input port
Required No
C Syntax void mdlSetInputPortComplexSignal(SimStruct *S, int_T port,
CSignal_T csig)
C
Arguments
S
SimStruct representing an S-Function block.
port
Index of a port.
csig
Numeric type of signal, either COMPLEX_NO (real) or COMPLEX_YES
(complex).
M Syntax SetInputPortComplexSignal(s, port, typeId)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
port
Integer value specifying index of port to be set.
typeId
Integer value specifying whether the port accepts real (0) or
complex (1) signals.
Description Simulink calls this routine to set the input port numeric type for
inputs that have this attribute set to COMPLEX_INHERITED. The
input csig is the proposed numeric type for this input port. This
method is only valid for simulation, and must be enclosed in a #if
defined(MATLAB_MEX_FILE) statement.
8-43
mdlSetInputPortComplexSignal
The S-function must check whether the proposed numeric type
is a valid type for the specified port. If it is valid, the S-function
must set the numeric type of the specified input port using
ssSetInputPortComplexSignal. Otherwise, it must report an error
using ssSetErrorStatus. The S-function can also set the numeric types
of other input and output ports with inherited numeric types. Simulink
reports an error if the S-function changes the numeric type of a port
whose numeric type is known.
If the S-function does not implement this routine, Simulink assumes
that the S-function accepts a real or complex signal and sets the input
port numeric type to the specified value.
Simulink will call this method until all input ports with inherited
numeric types have their numeric types specified.
Example See matlabroot/simulink/src/sdotproduct.c for an example of how
to use this function.
Languages C, C++, M
See Also ssSetErrorStatus, ssSetInputPortComplexSignal
8-44
mdlSetInputPortDataType
Purpose Set the data types of the signals accepted by an input port
Required No
C Syntax void mdlSetInputPortDataType(SimStruct *S, int_T port, DTypeId id)
C
Arguments
S
SimStruct representing an S-Function block.
port
Index of a port.
id
Data type ID.
M Syntax SetInputPortDataType(s, port, typeId)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
port
Integer value specifying index of port to be set.
typeId
Integer value specifying ID of ports data type. Use
s.getDatatypeName(typeId) to get the data types name.
Description Simulink calls this routine to set the data type of port when port
has an inherited data type. The data type id is the proposed data
type for this port. Data type IDs for the built-in data types can be
found in matlabroot/simulink/include/simstruc_types.h. This
method is only valid for simulation, and must be enclosed in a #if
defined(MATLAB_MEX_FILE) statement.
8-45
mdlSetInputPortDataType
The S-function must check whether the specified data type is a valid
data type for the specified port. If it is a valid data type, it must set the
data type of the input port using ssSetInputPortDataType. Otherwise,
it must report an error using ssSetErrorStatus.
The S-function can also set the data types of other input and output
ports if they are unknown. Simulink reports an error if the S-function
changes the data type of a port whose data type has been set.
If the block does not implement this routine, Simulink assumes that
the block accepts any data type and sets the input port data type to
the specified value.
Simulink will call this method until all input ports with inherited data
types have their data types specified.
Languages C, M
See Also ssSetErrorStatus, ssSetInputPortDataType
8-46
mdlSetInputPortDimensionInfo
Purpose Set the dimensions of the signals accepted by an input port
Required No
C Syntax void mdlSetInputPortDimensionInfo(SimStruct *S, int_T port,
const DimsInfo_T *dimsInfo)
C
Arguments
S
SimStruct representing an S-Function block.
port
Index of a port.
dimsInfo
Structure that specifies the signal dimensions supported by the
port.
See ssSetInputPortDimensionInfo for a description of this structure.
M Syntax SetInputPortDimensions(s, port, dims)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
port
Integer value specifying index of port to be set.
dims
1-D array that specifies the signal dimensions supported by the
port, e.g., [5] for a 5-element vector signal or [3 3] for a 3-by-3
matrix signal.
Description Simulink calls this method during dimension propagation with
candidate dimensions dimsInfo for port. If the proposed dimensions
are acceptable, this method should go ahead and set the actual
8-47
mdlSetInputPortDimensionInfo
port dimensions, using ssSetInputPortDimensionInfo. If they
are unacceptable, this method should generate an error via
ssSetErrorStatus.
This method is only valid for simulation, and must be enclosed in a #if
defined(MATLAB_MEX_FILE) statement.
Note This method can set the dimensions of any other input or output
port whose dimensions derive from the dimensions of port.
By default, Simulink calls this method only if it can fully determine the
dimensionality of port from the port to which it is connected. If it cannot
completely determine the dimensionality from port connectivity, it
invokes mdlSetDefaultPortDimensionInfo. If an S-function can fully
determine the port dimensionality from partial information, the function
should set the option SS_OPTION_ALLOW_PARTIAL_DIMENSIONS_CALL
in mdlInitializeSizes, using ssSetOptions. If this option is set,
Simulink invokes mdlSetInputPortDimensionInfo even if it can
only partially determine the dimensionality of the input port from
connectivity.
Simulink will call this method until all input ports with inherited
dimensions have their dimensions specified.
Example See matlabroot/simulink/src/sfun_matadd.c for an example of how
to use this function.
Languages C, C++, M
See Also ssSetErrorStatus
8-48
mdlSetInputPortFrameData
Purpose Specify whether an input port accepts frame data
Required No
C Syntax void mdlSetInputPortFrameData(SimStruct *S, int_T port,
Frame_T frameData)
C
Arguments
S
SimStruct representing an S-Function block.
port
Index of a port.
frameData
Frame data.
M Syntax SetInputPortSamplingMode(s, port, mode)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
port
Integer value specifying the index of port whose sampling mode
is to be set.
mode
Integer value specifying the sampling mode of the port (0 =
sample, 1 = frame).
Description This method is called with the candidate frame setting (FRAME_YES
or FRAME_NO) for an input port. If the proposed setting is acceptable,
the method should set the actual frame data setting using
ssSetInputPortFrameData. If the setting is unacceptable, an error
should be generated via ssSetErrorStatus. Note that any other input or
output ports whose frame data settings are implicitly defined by virtue
8-49
mdlSetInputPortFrameData
of knowing the frame data setting of the given port can also have their
frame data settings configured. This method is only valid for simulation,
and must be enclosed in a #if defined(MATLAB_MEX_FILE) statement.
Simulink will call this method until all input ports with inherited frame
settings have their frame settings specified.
The use of frame-based signals (mode has a value of 1) requires a Signal
Processing Blockset license.
Languages C, C++, M
See Also ssSetInputPortFrameData, ssSetOutputPortFrameData,
ssSetErrorStatus
8-50
mdlSetInputPortSampleTime
Purpose Set the sample time of an input port that inherits its sample time from
the port to which it is connected
Required No
C Syntax void mdlSetInputPortSampleTime(SimStruct *S, int_T port,
real_T sampleTime, real_T offsetTime)
C
Arguments
S
SimStruct representing an S-Function block.
port
Index of a port.
sampleTime
Inherited sample time for port.
offsetTime
Inherited offset time for port.
M Syntax SetInputPortSampleTime(s, port, time)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
port
Integer value specifying the index of port whose sampling mode
is to be set.
time
Two-element array, [period offset], that specifies the period
and offset of the times that this port samples its input.
Description Simulink invokes this method with the sample time that port
inherits from the port to which it is connected. If the inherited
sample time is acceptable, this method should set the sample time of
8-51
mdlSetInputPortSampleTime
port to the inherited time, using ssSetInputPortSampleTime and
ssSetInputPortOffsetTime. If the sample time is unacceptable, this
method should generate an error via ssSetErrorStatus. Note that
any other input or output ports whose sample times are implicitly
defined by virtue of knowing the sample time of the given port can also
have their sample times set via calls to ssSetInputPortSampleTime or
ssSetOutputPortSampleTime. This method is only valid for simulation,
and must be enclosed in a #if defined(MATLAB_MEX_FILE) statement.
Simulink invokes this method until all input ports with inherited
sample times are specified.
When inherited port-based sample times are specified, the sample time
is guaranteed to be one of the following where 0.0 < period < inf
and 0.0 <= offset < period.
Sample Time Offset Time
Continuous 0.0 0.0
Discrete period offset
Constant, triggered, and variable-step sample times are not propagated
to S-functions with port-based sample times.
Generally mdlSetInputPortSampleTime is called once per port with
the input port sample time. However, there can be cases where this
function is called more than once. This happens when the simulation
engine is converting continuous sample times to continuous but fixed
in minor steps sample times. When this occurs, the original values of
the sample times specified in mdlInitializeSizes are restored before
this method is called again.
The final sample time specified at the port can be different from (but
equivalent to) the sample time specified by this method. This occurs
when
The model uses a fixed-step solver and the port has a continuous but
fixed in minor step sample time. In this case, Simulink converts the
sample time to the fundamental sample time for the model.
8-52
mdlSetInputPortSampleTime
Simulink adjusts the sample time to be as numerically sound as
possible. For example, Simulink converts [0.2499999999999, 0]
to [0.25, 0].
The S-function can examine the final sample times in
mdlInitializeSampleTimes.
Languages C, C++, M
See Also ssSetInputPortSampleTime, ssSetOutputPortSampleTime,
mdlInitializeSampleTimes
8-53
mdlSetInputPortWidth
Purpose Set the width of an input port that accepts 1-D (vector) signals
Required No
C Syntax void mdlSetInputPortWidth(SimStruct *S, int_T port, int_T width)
C
Arguments
S
SimStruct representing an S-Function block.
port
Index of a port.
width
Width of signal.
Description This method is called with the candidate width for a dynamically
sized port. If the proposed width is acceptable, the method should
set the actual port width using ssSetInputPortWidth. If the size is
unacceptable, an error should be generated via ssSetErrorStatus. Note
that any other dynamically sized input or output ports whose widths
are implicitly defined by virtue of knowing the width of the given port
can also have their widths set via calls to ssSetInputPortWidth or
ssSetOutputPortWidth. This method is only valid for simulation, and
must be enclosed in a #if defined(MATLAB_MEX_FILE) statement.
Simulink invokes this method until all dynamically sized input ports
are configured.
Languages C
See Also ssSetInputPortWidth, ssSetOutputPortWidth, ssSetErrorStatus
8-54
mdlSetOutputPortComplexSignal
Purpose Set the numeric types (real, complex, or inherited) of the signals
accepted by an output port
Required No
C Syntax void mdlSetOutputPortComplexSignal(SimStruct *S, int_T port,
CSignal_T csig)
C
Arguments
S
SimStruct representing an S-Function block.
port
Index of a port.
csig
Numeric type of signal, either COMPLEX_NO (real) or COMPLEX_YES
(complex).
M Syntax SetOutputPortComplexSignal(s, port, typeId)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
port
Integer value specifying the index of port to be set.
typeId
Integer value specifying whether the port produces real (0) or
complex (1) signals.
Description Simulink calls this routine to set the output port numeric type for
outputs that have this attribute set to COMPLEX_INHERITED. The
input argument csig is the proposed numeric type for this output
port. The S-function must check whether the specified numeric type
is a valid type for the specified port. If it is valid, the S-function
8-55
mdlSetOutputPortComplexSignal
must set the numeric type of the specified output port using
ssSetOutputPortComplexSignal. Otherwise, it must report an error,
using ssSetErrorStatus. The S-function can also set the numeric types
of other input and output ports with unknown numeric types. Simulink
reports an error if the S-function changes the numeric type of a port
whose numeric type is known. This method is only valid for simulation,
and must be enclosed in a #if defined(MATLAB_MEX_FILE) statement.
If the S-function does not implement this routine, Simulink assumes
that the S-function accepts a real or complex signal and sets the output
port numeric type to the specified value.
Simulink will call this method until all output ports with inherited
numeric types have their numeric types specified.
Example See matlabroot/simulink/src/sdotproduct.c for an example of how
to use this function.
Languages C, C++, M
See Also ssSetOutputPortComplexSignal, ssSetErrorStatus
8-56
mdlSetOutputPortDataType
Purpose Set the data type of the signals emitted by an output port
Required No
C Syntax void mdlSetOutputPortDataType(SimStruct *S, int_T port,
DTypeId id)
C
Arguments
S
SimStruct representing an S-Function block.
port
Index of an output port.
id
Data type ID.
M Syntax SetOutputPortDataType(s, port, typeId)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
port
Integer value specifying index of port to be set.
typeId
Integer value specifying ID of ports data type. Use
s.getDatatypeName(typeId) to get the data types name.
Description Simulink calls this routine to set the data type of port when port has
an inherited data type. The data type IDid is the proposed data type
for this port. Data type IDs for the built-in data types can be found in
matlabroot/simulink/include/simstruc_types.h. The S-function
must check whether the specified data type is a valid data type for the
specified port. If it is a valid data type, it must set the data type of port
using ssSetOutputPortDataType. Otherwise, it must report an error,
8-57
mdlSetOutputPortDataType
using ssSetErrorStatus. This method is only valid for simulation, and
must be enclosed in a #if defined(MATLAB_MEX_FILE) statement.
The S-function can also set the data types of other input and output
ports if their data types have not been set. Simulink reports an error
if the S-function changes the data type of a port whose data type has
been set.
If the block does not implement this method, Simulink assumes that
the block supports any data type and sets the output port data type to
the specified value.
Simulink will call this method until all output ports with inherited data
types have their data types specified.
Languages C, C++, M
See Also ssSetOutputPortDataType, ssSetErrorStatus
8-58
mdlSetOutputPortDimensionInfo
Purpose Set the dimensions of the signals accepted by an output port
Required No
C Syntax void mdlSetOutputPortDimensionInfo(SimStruct *S, int_T port,
const DimsInfo_T *dimsInfo)
C
Arguments
S
SimStruct representing an S-Function block or a Simulink model.
port
Index of a port.
dimsInfo
Structure that specifies the signal dimensions supported by port.
See ssSetInputPortDimensionInfo for a description of this structure.
M Syntax SetOutputPortDimensions(s, port, dims)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
port
Integer value specifying the index of the port to be set.
dims
1-D array that specifies the signal dimensions supported by the
port, e.g., [5] for a 5-element vector signal or [3 3] for a 3-by-3
matrix signal.
Description Simulink calls this method with candidate dimensions dimsInfo
for port. If the proposed dimensions are acceptable, this method
should go ahead and set the actual port dimensions, using
ssSetOutputPortDimensionInfo. If they are unacceptable, this
8-59
mdlSetOutputPortDimensionInfo
method should generate an error via ssSetErrorStatus. This
method is only valid for simulation, and must be enclosed in a #if
defined(MATLAB_MEX_FILE) statement.
Note This method can set the dimensions of any other input or output
port whose dimensions derive from the dimensions of port.
By default, Simulink calls this method only if it can fully determine the
dimensionality of port from the port to which it is connected. If it cannot
completely determine the dimensionality from port connectivity, it
invokes mdlSetDefaultPortDimensionInfo. If an S-function can fully
determine the port dimensionality from partial information, the function
should set the option SS_OPTION_ALLOW_PARTIAL_DIMENSIONS_CALL
in mdlInitializeSizes, using ssSetOptions. If this option is set,
Simulink invokes mdlSetOutputPortDimensionInfo even if it can
only partially determine the dimensionality of the output port from
connectivity. Simulink will call this method until all output ports with
inherited dimensions have their dimensions specified.
Example See matlabroot/simulink/src/sfun_matadd.c for an example of how
to use this function.
Languages C, C++, M
See Also ssSetErrorStatus, ssSetOutputPortDimensionInfo
8-60
mdlSetOutputPortSampleTime
Purpose Set the sample time of an output port that inherits its sample time from
the port to which it is connected
Required No
C Syntax void mdlSetOutputPortSampleTime(SimStruct *S, int_T port,
real_T sampleTime, real_T offsetTime)
C
Arguments
S
SimStruct representing an S-Function block.
port
Index of a port.
sampleTime
Inherited sample time for port.
offsetTime
Inherited offset time for port.
M Syntax SetOutputPortSampleTime(s, port, time)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
port
Integer value specifying the index of port whose sampling mode
is to be set.
time
Two-element array, [period offset], that specifies the period
and offset of the times that this port produces output.
Description Simulink calls this method with the sample time that port inherits
from the port to which it is connected. If the inherited sample time
is acceptable, this method should set the sample time of port to the
8-61
mdlSetOutputPortSampleTime
inherited sample time and offset time, using ssSetOutputPortSampleTime
and ssSetOutputPortOffsetTime, or
pd = s.OutputPort(port);
pd.SampleTime = time;
in the case of a Level-2 M-file S-function.
If the inherited sample time is unacceptable, this method should
generate an error via ssSetErrorStatus. Note that this method can set
the sample time of any other input or output port whose sample time
derives fromthe sample time of port, using ssSetInputPortSampleTime
or ssSetOutputPortSampleTime or the SampleTime property of the
Simulink.BlockPortData object associated with the port in the case
of Level-2 M-file S-functions. This method is only valid for simulation,
and must be enclosed in a #if defined(MATLAB_MEX_FILE) statement
when used in a C-MEX S-function.
Normally, sample times are propagated forward; however, if sources
feeding this block have inherited sample times, Simulink might
choose to back-propagate known sample times to this block. When
back-propagating sample times, this method is called in succession for
all inherited output port signals.
See mdlSetInputPortSampleTime for more information about when this
method is called.
Languages C, M
See Also ssSetOutputPortSampleTime, ssSetErrorStatus,
ssSetInputPortSampleTime, ssSetOutputPortSampleTime,
mdlSetInputPortSampleTime, Simulink.MSFcnRunTimeBlock,
Simulink.BlockPortData
8-62
mdlSetOutputPortWidth
Purpose Set the width of an output port that outputs 1-D (vector) signals
Required No
C Syntax void mdlSetOutputPortWidth(SimStruct *S, int_T port, int_T width)
C
Arguments
S
SimStruct representing an S-Function block.
port
Index of a port.
width
Width of signal.
Description This method is called with the candidate width for a dynamically sized
port. If the proposed width is acceptable, the method should go ahead
and set the actual port width, using ssSetOutputPortWidth. If the size
is unacceptable, an error should be generated via ssSetErrorStatus.
Note that any other dynamically sized input or output ports whose
widths are implicitly defined by virtue of knowing the width of the given
port can also have their widths set via calls to ssSetInputPortWidth or
ssSetOutputPortWidth. This method is only valid for simulation, and
must be enclosed in a #if defined(MATLAB_MEX_FILE) statement.
Languages C
See Also ssSetInputPortWidth, ssSetOutputPortWidth, ssSetErrorStatus
8-63
mdlSetWorkWidths
Purpose Specify the sizes of the work vectors and create the run-time parameters
required by this S-function
Required No
C Syntax void mdlSetWorkWidths(SimStruct *S)
C
Arguments
S
SimStruct representing an S-Function block.
M Syntax PostPropagationSetup(s)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
Description Simulink calls this optional method to enable this S-function to set the
sizes of state and work vectors that it needs to store global data and
to create run-time parameters (see Run-Time Parameters on page
7-7). Simulink invokes this method after it has determined the input
port width, output port width, and sample times of the S-function.
This allows the S-function to size the state and work vectors based
on the number and sizes of inputs and outputs and/or the number
of sample times. This method specifies the state and work vector
sizes via the macros ssGetNumContStates, ssSetNumDiscStates,
ssSetNumRWork, ssSetNumIWork, ssSetNumPWork, ssSetNumModes, and
ssSetNumNonsampledZCs.
A C-MEX S-function needs to implement this method only if it does
not know the sizes of all the work vectors it requires when Simulink
invokes the functions mdlInitializeSizes method. If this S-function
implements mdlSetWorkWidths, it should initialize the sizes of any work
vectors that it needs to DYNAMICALLY_SIZED in mdlInitializeSizes,
even for those whose exact size it knows at that point. The S-function
8-64
mdlSetWorkWidths
should then specify the actual size in mdlSetWorkWidths. This
method is only valid for simulation, and must be enclosed in a #if
defined(MATLAB_MEX_FILE) statement.
A Level-2 M-file S-function must implement this method if any Dwork
vectors are used in the S-function. In the case of M-file S-functions, this
method sets the number of Dwork vectors and initializes their attributes.
For example, the following code in the PostPropagationSetup method
specifies the usage type for the Dwork vector:
block.DWork(1).UsageType = type;
where block is an instance of the Simulink.MSFcnRunTimeBlock class
representing the S-Function block and type is one of the following:
DWork
DState
Scratch
Mode
For a full example of a Level-2 M-file S-function using Dwork vectors,
see the file matlabroot/toolbox/simulink/simdemos/adapt_lms.m
used in the Simulink model sldemo_msfcn_lms.mdl.
Languages Ada, C, M
See Also mdlInitializeSizes
8-65
mdlSimStatusChange
Purpose Respond to a pause or resumption of the simulation of the model that
contains this S-function
Required No
C Syntax void mdlSimStatusChange(SimStruct *S,
ssSimStatusChangeType simStatus)
C
Arguments
S
SimStruct representing an S-Function block.
simStatus
Status of the simulation, either SIM_PAUSE or SIM_CONTINUE.
M Syntax SimStatusChange(s, status)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
status
Status of the simulation, either 0 when paused or 1 when
continued.
Description Simulink calls this routine when a simulation of the model containing S
pauses or resumes. This method is only valid for simulation, and must
be enclosed in a #if defined(MATLAB_MEX_FILE) statement.
Example #if defined(MATLAB_MEX_FILE)
#define MDL_SIM_STATUS_CHANGE
static void mdlSimStatusChange(SimStruct *S,
ssSimStatusChangeType simStatus) {
if (simStatus == SIM_PAUSE) {
slPrintf("Pause has been called! \n");
} else if (simStatus == SIM_CONTINUE) {
8-66
mdlSimStatusChange
slPrintf("Continue has been called! \n");
}
}
#endif
Languages C
8-67
mdlStart
Purpose Initialize the state vectors of this S-function
Required No
C Syntax void mdlStart(SimStruct *S)
C
Arguments
S
SimStruct representing an S-Function block.
M Syntax Start(s)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
Description Simulink invokes this optional method at the beginning of a simulation.
It should initialize the continuous and discrete states, if any, of this
S-Function block. Use ssGetContStates and/or ssGetDiscStates to
get the states. This method can also perform any other initialization
activities that this S-function requires, such as allocating memory or
setting up user data.
Languages Ada, C, M
Example See matlabroot/simulink/src/sfun_directlook.c for an example of
how to use this function.
See Also mdlInitializeConditions, ssGetContStates, ssGetDiscStates
8-68
mdlTerminate
Purpose Perform any actions required at termination of the simulation
Required Yes
C Syntax void mdlTerminate(SimStruct *S)
C
Arguments
S
SimStruct representing an S-Function block.
M Syntax Terminate(s)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
Description This method should perform any actions, such as freeing memory, that
must be performed at the end of simulation or when an S-Function
block is destroyed (e.g., when it is deleted from a model). The option
SS_OPTION_CALL_TERMINATE_ON_EXIT determines whether Simulink
invokes this method. If this option is not set, Simulink invokes
mdlTerminate at the end of the simulation only if the mdlStart method
of at least one block in the model has executed without error during
the simulation. If this option is set, Simulink always invokes the
mdlTerminate method at the end of a simulation run and whenever
it destroys a block.
Use the UNUSED_ARG macro if the mdlTerminate function does not
perform any actions that require the SimStruct S to indicate that the
S input argument is required but not used in the body of the callback.
To do this, insert the line
UNUSED_ARG(S)
after any declarations in mdTerminate.
8-69
mdlTerminate
Note When generating code for a noninlined S-function that
contains this method, make sure the method is not wrapped in a #if
defined(MATLAB_MEX_FILE) statement. For example:
#if defined(MATLAB_MEX_FILE)
static void mdlTerminate(SimStruct *S)
{
/* Add mdlTerminate code here *
}
#endif
The define statement makes the mdlTerminate method available only
to a MATLAB MEX-file. If the S-function is not inlined, Real-Time
Workshop cannot use this method, resulting in link or run-time errors.
Example Suppose your S-function allocates blocks of memory in mdlStart and
saves pointers to the blocks in a PWork vector. The following code
fragment would free this memory.
{
int i;
for (i = 0; i<ssGetNumPWork(S); i++) {
if (ssGetPWorkValue(S,i) != NULL) {
free(ssGetPWorkValue(S,i));
}
}
}
Languages Ada, C, M
See Also ssSetOptions
8-70
mdlUpdate
Purpose Update a blocks states
Required No
C Syntax void mdlUpdate(SimStruct *S, int_T tid)
C
Arguments
S
SimStruct representing an S-Function block.
tid
Task ID.
M Syntax Update(s)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
Description Simulink invokes this optional method at each major simulation time
step. The method should compute the S-functions states at the current
time step and store the states in the S-functions state vector. The
method can also perform any other tasks that the S-function needs to
perform at each major time step.
Use this code if your S-function has one or more discrete states or does
not have direct feedthrough.
The reason for this is that most S-functions that do not have discrete
states but do have direct feedthrough do not have update functions.
Therefore, Simulink is able to eliminate the need for the extra call in
these circumstances.
If your S-function needs to have its mdlUpdate routine called and
it does not satisfy either of the above two conditions, specify that it
has a discrete state, using the ssSetNumDiscStates macro in the
mdlInitializeSizes function.
8-71
mdlUpdate
The tid (task ID) argument specifies the task running when the
mdlOutputs routine is invoked. You can use this argument in the
mdlUpdate routine of a multirate S-Function block to encapsulate
task-specific blocks of code (see Multirate S-Function Blocks on page
7-37).
Use the UNUSED_ARG macro if the S-function does not contain
task-specific blocks of code to indicate that the tid input argument is
required but not used in the body of the callback. To do this, insert
the line
UNUSED_ARG(tid)
after the declarations in mdlUpdate.
Note When generating code for a noninlined S-function that
contains this method, make sure the method is not wrapped in a #if
defined(MATLAB_MEX_FILE) statement. For example:
#define MDL_UPDATE
#if defined(MDL_UPDATE) && defined(MATLAB_MEX_FILE)
static void mdlUpdate(SimStruct *S)
{
/* Add mdlUpdate code here *
}
#endif
The define statement makes the mdlUpdate method available only
to a MATLAB MEX-file. If the S-function is not inlined, Real-Time
Workshop cannot use this method, resulting in link or run-time errors.
Example For an example that uses this function to update discrete states, see
matlabroot/simulink/src/dsfunc.c. For an example that uses this
function to update the transfer function coefficients of a time-varying
continuous transfer function, see matlabroot/simulink/src/stvctf.c.
8-72
mdlUpdate
Languages Ada, C, C++, M
See Also mdlDerivatives, ssGetContStates, ssGetDiscStates
8-73
mdlZeroCrossings
Purpose Update zero-crossing vector
Required No
C Syntax void mdlZeroCrossings(SimStruct *S)
C
Arguments
S
SimStruct representing an S-Function block.
M Syntax ZeroCrossings(s)
M
Arguments
s
Instance of Simulink.MSFcnRunTimeBlock class representing the
S-Function block.
Description An S-function needs to provide this optional method only if it does
zero-crossing detection. Implementing zero-crossing detection typically
requires using the zero-crossing and mode work vectors to determine
when a zero crossing occurs and how the S-functions outputs should
respond to this event. The mdlZeroCrossings method should update
the S-functions zero-crossing vector, using ssGetNonsampledZCs.
You can use the optional mdlZeroCrossings routine when your
S-function has registered the CONTINUOUS_SAMPLE_TIME and has
nonsampled zero crossings (ssGetNumNonsampledZCs(S) > 0). The
mdlZeroCrossings routine is used to provide Simulink with signals
that are to be tracked for zero crossings. These are typically
Continuous signals entering the S-function
Internally generated signals that cross zero when a discontinuity
would normally occur in mdlOutputs
Thus, the zero-crossing signals are used to locate the discontinuities and
end the current time step at the point of the zero crossing. To provide
8-74
mdlZeroCrossings
Simulink with zero-crossing signals, mdlZeroCrossings updates the
ssGetNonsampleZCs(S) vector.
Example For an example, see matlabroot/simulink/src/sfun_zc_sat.c. A
detailed description of this example can be found in Work Vectors and
Zero Crossings on page 7-44 in the Simulink documentation.
Languages C, C++, M
See Also mdlInitializeSizes, ssGetNonsampledZCs
8-75
mdlZeroCrossings
8-76
9
SimStruct Functions By
Category
Introduction (p. 9-2) Overview of SimStruct macros and
functions.
SimStruct Macros and Functions
Listed by Usage (p. 9-3)
SimStruct functions listed by usage.
9 SimStruct Functions By Category
Introduction
In this section...
About SimStruct Functions on page 9-2
Language Support on page 9-2
The SimStruct on page 9-2
About SimStruct Functions
Simulink provides a set of functions for accessing the fields of an S-functions
simulation data structure (SimStruct). S-function callback methods use these
functions to store and retrieve information about an S-function.
Language Support
Some SimStruct functions are available only in some of the languages
supported by Simulink. The reference page for each SimStruct macro or
function lists the languages in which it is available. If the SimStruct function
is available in C, the reference page gives its C syntax. Otherwise, it gives
its syntax in the language in which it is available.
Note Most SimStruct functions available in C are implemented as C macros.
The SimStruct
The file matlabroot/simulink/include/simstruc.h is a C language header
file that defines the Simulink data structure and the SimStruct access
macros. It encapsulates all the data relating to the model or S-function,
including block parameters and outputs.
There is one SimStruct data structure allocated for the Simulink model.
Each S-function in the model has its own SimStruct associated with it.
The organization of these SimStructs is much like a directory tree. The
SimStruct associated with the model is the root SimStruct. The SimStructs
associated with the S-functions are the child SimStructs.
9-2
SimStruct Macros and Functions Listed by Usage
SimStruct Macros and Functions Listed by Usage
SimStruct Macros and Functions Listed by Usage
Data Type
Dialog Box Parameters
Error Handling and Status
Function Call
I/O Port Signal Specification
I/O Port Signal Dimensions
I/O Port Signal Access on page 9-10
Run-Time Parameters on page 9-12
Sample Time on page 9-13
Simulation Information on page 9-15
State and Work Vector on page 9-17
Miscellaneous
Real-Time Workshop
Data Type
Macro Description
ssGetDataTypeId Get the ID for a data type.
ssGetDataTypeIdAliasedThruTo Get the ID for the built-in data type
associated with a data type alias.
ssGetDataTypeName Get a data types name.
ssGetDataTypeSize Get a data types size.
ssGetDataTypeZero Get the zero representation of a data
type.
ssGetInputPortDataType Get the data type of an input port.
9-3
9 SimStruct Functions By Category
Data Type (Continued)
Macro Description
ssGetNumDataTypes Get the number of data types defined by
an S-function or the model.
ssGetOutputPortDataType Get the data type of an output port.
ssGetOutputPortSignal Get an output signal of any type except
double.
ssRegisterDataType Register a data type.
ssSetDataTypeSize Specify the size of a data type.
ssSetDataTypeZero Specify the zero representation of a data
type.
ssSetInputPortDataType Specify the data type of signals accepted
by an input port.
ssSetOutputPortDataType Specify the data type of an output port.
Dialog Box Parameters
Macro Description
ssGetDTypeIdFromMxArray Get the Simulink data type of a dialog
parameter.
ssGetNumParameters Get the number of parameters that this
block has (Ada only).
ssGetNumSFcnParams Get the number of parameters that an
S-function expects.
ssGetSFcnParam Get a parameter entered by a user in the
S-Function block dialog box.
ssGetSFcnParamsCount Get the actual number of parameters
specified by the user.
ssSetNumSFcnParams Set the number of parameters that an
S-function expects.
ssSetParameterName Set the name of a parameter (Ada only).
9-4
SimStruct Macros and Functions Listed by Usage
Dialog Box Parameters (Continued)
Macro Description
ssSetParameterTunable Set the tunability of a parameter (Ada only).
ssSetSFcnParamNotTunable Obsolete.
ssSetSFcnParamTunable Specify the tunability of a dialog box
parameter.
Error Handling and Status
Macro Description
ssGetErrorStatus Get a string that identifies the last error.
ssPrintf Print a variable-content msg.
ssSetErrorStatus Report errors.
ssWarning Display a warning message.
Function Call
Macro Description
ssCallSystemWithTid Execute a function-call subsystem connected
to an S-function.
ssDisableSystemWithTid Disable a function-call subsystem connected
to this S-function block.
ssEnableSystemWithTid Enable a function-call subsystem connected
to this S-function.
ssGetExplicitFCSSCtrl Determine whether this S-function explicitly
enables and disables the function-call
subsystem that it invokes.
9-5
9 SimStruct Functions By Category
Function Call (Continued)
Macro Description
ssSetCallSystemOutput Specify that an output port element issues a
function call.
ssSetExplicitFCSSCtrl Specify whether an S-function explicitly
enables and disables the function-call
subsystem that it calls.
Input and Output Ports
I/O Port Signal Specification
Macro Description
ssGetInputPortComplexSignal Get the numeric type (complex
or real) of an input port.
ssGetInputPortDataType Get the data type of an input
port.
ssGetInputPortDirectFeedThrough Determine whether an input
port has direct feedthrough.
ssGetInputPortFrameData Determine whether a port
accepts signal frames.
ssGetInputPortOffsetTime Determine the offset time of an
input port.
ssGetInputPortRequiredContiguous Determine whether the signal
elements entering a port must be
contiguous.
ssGetInputPortSampleTime Determine the sample time of an
input port.
ssGetInputPortSampleTimeIndex Get the sample time index of an
input port.
ssGetOutputPortComplexSignal Get the numeric type (complex
or real) of an output port.
9-6
SimStruct Macros and Functions Listed by Usage
I/O Port Signal Specification (Continued)
Macro Description
ssGetOutputPortDataType Get the data type of an output
port.
ssGetOutputPortFrameData Determine whether a port
outputs signal frames.
ssGetOutputPortOffsetTime Determine the offset time of an
output port.
ssGetOutputPortSampleTime Determine the sample time of an
output port.
ssSetInputPortComplexSignal Set the numeric type (real or
complex) of an input port.
ssSetInputPortDataType Set the data type of an input
port.
ssSetInputPortDirectFeedThrough Specify that an input port is a
direct-feedthrough port.
ssSetInputPortFrameData Specify whether a port accepts
signal frames.
ssSetInputPortOffsetTime Specify the sample time offset
for an input port.
ssSetInputPortRequiredContiguous Specify that the signal elements
entering a port must be
contiguous.
ssSetInputPortSampleTime Set the sample time of an input
port.
ssSetNumInputPorts Set the number of input ports on
an S-Function block.
ssSetNumOutputPorts Specify the number of output
ports on an S-Function block.
ssSetOneBasedIndexInputPort Specify that an input port
expects one-based indices.
9-7
9 SimStruct Functions By Category
I/O Port Signal Specification (Continued)
Macro Description
ssSetOneBasedIndexOutputPort Specify that an output port emits
one-based indices.
ssSetOutputPortComplexSignal Specify the numeric type (real or
complex) of this port.
ssSetOutputPortDataType Specify the data type of an
output port.
ssSetOutputPortFrameData Specify whether a port outputs
framed data.
ssSetOutputPortOffsetTime Specify the sample time offset
value of an output port.
ssSetOutputPortSampleTime Specify the sample time of an
output port.
ssSetZeroBasedIndexInputPort Specify that an input port
expects zero-based indices.
ssSetZeroBasedIndexOutputPort Specify that an output port emits
zero-based indices.
I/O Port Signal Dimensions
Macro Description
ssAllowSignalsWithMoreThan2D Enable S-function to work with
multidimensional signals.
ssGetInputPortDimensions Get the dimensions of the signal
accepted by an input port.
ssGetInputPortNumDimensions Get the dimensionality of the
signals accepted by an input
port.
ssGetInputPortWidth Determine the width of an input
port.
9-8
SimStruct Macros and Functions Listed by Usage
I/O Port Signal Dimensions (Continued)
Macro Description
ssGetOutputPortDimensions Get the dimensions of the signal
leaving an output port.
ssGetOutputPortNumDimensions Get the number of dimensions of
an output port.
ssGetOutputPortWidth Determine the width of an
output port.
ssSetInputPortDimensionInfo Set the dimensionality of an
input port.
ssSetInputPortMatrixDimensions Specify dimension information
for an input port that accepts
matrix signals.
ssSetInputPortVectorDimension Specify dimension information
for an input port that accepts
vector signals.
ssSetInputPortWidth Set the width of a 1-D (vector)
input port.
ssSetOutputPortDimensionInfo Specify the dimensionality of an
output port.
ssSetOutputPortMatrixDimensions Specify dimension information
for an output port that emits
matrix signals.
ssSetOutputPortVectorDimension Specify dimension information
for an output port that emits
vector signals.
ssSetOutputPortWidth Specify the width of a 1-D
(vector) output port.
9-9
9 SimStruct Functions By Category
I/O Port Signal Dimensions (Continued)
Macro Description
ssSetOutputPortMatrixDimensions Specify the dimensions of a 2-D
(matrix) signal.
ssSetVectorMode Specify the vector mode that an
S-function supports.
I/O Port Signal Access
Macro Description
ssGetInputPortBufferDstPort Determine the output port that
is overwriting an input ports
memory buffer.
ssGetInputPortConnected Determine whether an
S-Function block port is
connected to a nonvirtual block.
ssGetInputPortOptimOpts Determine the reusability
setting of the memory allocated
to the input port of an S-function.
ssGetInputPortOverWritable Determine whether an input
port can be overwritten.
ssGetInputPortRealSignal Get the address of a real,
contiguous signal entering an
input port.
ssGetInputPortRealSignalPtrs Access the signal elements
connected to an input port.
ssGetInputPortSignal Get the address of a contiguous
signal entering an input port.
ssGetInputPortSignalAddress Get the address of an input ports
signal (Ada only).
ssGetInputPortSignalPtrs Get pointers to input signal
elements of type other than
double.
9-10
SimStruct Macros and Functions Listed by Usage
I/O Port Signal Access (Continued)
Macro Description
ssGetNumInputPorts Can be used in any routine
(except mdlInitializeSizes) to
determine how many input ports
a block has.
ssGetNumOutputPorts Can be used in any routine
(except mdlInitializeSizes)
to determine how many output
ports a block has.
ssGetOutputPortConnected Determine whether an output
port is connected to a nonvirtual
block.
ssGetOutputPortBeingMerged Determine whether the output
of this block is connected to a
Merge block.
ssGetOutputPortOptimOpts Determine the reusability of the
memory allocated to the output
port of an S-function.
ssGetOutputPortRealSignal Access the elements of a signal
connected to an output port.
ssGetOutputPortSignal Get the vector of signal elements
emitted by an output port.
ssGetOutputPortSignalAddress Get the address of an output
ports signal (Ada only).
ssSetInputPortOptimOpts Specify the reusability of the
memory allocated to the input
port of an S-function.
ssSetInputPortOverWritable Specify whether an input port is
overwritable by an output port.
9-11
9 SimStruct Functions By Category
I/O Port Signal Access (Continued)
Macro Description
ssSetOutputPortOptimOpts Specify the reusability of the
memory allocated to the output
port of an S-function.
ssSetOutputPortOverwritesInputPort Specify whether an output port
can share its memory buffer with
an input port.
Run-Time Parameters
These macros allow you to create, update, and access run-time parameters
corresponding to a blocks dialog parameters.
Run-Time Parameters
Macro Description
ssGetNumRunTimeParams Get the number of
run-time parameters
created by this
S-function.
ssGetRunTimeParamInfo Get the attributes of
a specified run-time
parameter.
ssRegAllTunableParamsAsRunTimeParams Register all tunable
dialog parameters as
run-time parameters.
ssRegDlgParamAsRunTimeParam Register a run-time
parameter.
ssSetNumRunTimeParams Specify the number of
run-time parameters
to be created by this
S-function.
9-12
SimStruct Macros and Functions Listed by Usage
Run-Time Parameters (Continued)
Macro Description
ssSetRunTimeParamInfo Specify the attributes
of a specified run-time
parameter.
ssUpdateAllTunableParamsAsRunTimeParams Update all run-time
parameters
corresponding to
tunable dialog
parameters.
ssUpdateDlgParamAsRunTimeParam Update a run-time
parameter.
ssUpdateRunTimeParamData Update the value of
a specified run-time
parameter.
ssUpdateRunTimeParamInfo Update the attributes
of a specified run-time
parameter from the
attributes of the
corresponding dialog
parameters.
Sample Time
Macro Description
ssGetInputPortSampleTime Determine the sample time of an
input port.
ssGetInputPortSampleTimeIndex Get the sample time index of an
input port.
ssGetNumSampleTimes Get the number of sample times an
S-function has.
ssGetOffsetTime Determine one of an S-functions
sample time offsets.
9-13
9 SimStruct Functions By Category
Sample Time (Continued)
Macro Description
ssGetOutputPortSampleTime Determine the sample time of an
output port.
ssGetPortBasedSampleTimeBlockIs-
Triggered
Determine whether a block that
uses port-based sample times
resides in a triggered subsystem.
ssGetSampleTime Determine one of an S-functions
sample times.
ssGetSampleTimeOffset Get the offset of the current sample
time (Ada only).
ssGetSampleTimePeriod Get the period of the current sample
time (Ada only).
ssGetTNext Get the time of the next sample
hit in a discrete S-function with a
variable sample time.
ssIsContinuousTask Determine whether a specified rate
is the continuous rate.
ssIsSampleHit Determine the sample rate at which
an S-function is operating.
ssIsSpecialSampleHit Determine whether the current
sample time hits two specified
rates.
ssSampleAndOffsetAreTriggered Determine whether a sample time
and offset value pair indicate a
triggered sample time.
ssSetInputPortSampleTime Set the sample time of an input
port.
ssSetModelReferenceSampleTime-
InheritanceRule
Specify whether use of an
S-function in a submodel prevents
the submodel from inheriting its
sample time from the parent model.
9-14
SimStruct Macros and Functions Listed by Usage
Sample Time (Continued)
Macro Description
ssSetNumSampleTimes Set the number of sample times an
S-function has.
ssSetOffsetTime Specify the offset of a sample time.
ssSetSampleTime Specify a sample time for an
S-function.
ssSetTNext Specify the time of the next sample
hit in an S-function.
Simulation Information
Macro Description
ssGetAbsTol Get the absolute tolerances used by a models
variable-step solver.
ssGetBlockReduction Determine whether a block has requested
block reduction before the simulation has
begun and whether it has actually been
reduced after the simulation loop has begun.
ssGetErrorStatus Get a string that identifies the last error.
ssGetInlineParameters Determine whether the user has set the
inline parameters option for the model
containing this S-function.
ssGetSimMode Determine the context in which an
S-function is being invoked: normal
simulation, external-mode simulation,
model editor, etc.
ssGetSolverMode Get the solver mode being used to solve the
S-function.
ssGetSolverName Get the name of the solver being used for
the simulation.
9-15
9 SimStruct Functions By Category
Simulation Information (Continued)
Macro Description
ssGetStateAbsTol Get the absolute tolerance used by the
models variable-step solver for a specified
state.
ssGetStopRequested Get the value of the simulation stop
requested flag.
ssGetT Get the current base simulation time.
ssGetTaskTime Get the current time for a task.
ssGetTFinal Get the end time of the current simulation.
ssGetTNext Get the time of the next sample hit.
ssGetTStart Get the start time of the current simulation.
ssIsFirstInitCond Determine whether this is the first call to
mdlInitializeConditions.
ssIsMajorTimeStep Determine whether the current time step is
a major time step.
ssIsMinorTimeStep Determine whether the current time step is
a minor time step.
ssIsVariableStepSolver Determine whether the current solver is a
variable-step solver.
ssSetBlockReduction Request that Simulink attempt to reduce a
block.
ssSetSolverNeedsReset Ask Simulink to reset the solver.
ssSetStopRequested Ask Simulink to terminate the simulation at
the end of the current time step.
9-16
SimStruct Macros and Functions Listed by Usage
State and Work Vector
These macros enable an S-function to access and set the S-functions work
vectors.
State and Work Vector
Macro Description
ssGetContStateAddress Get the address of a blocks continuous state
vector.
ssGetContStates Get an S-functions continuous states.
ssGetDiscStates Get an S-functions discrete states.
ssGetDWork Get a DWork vector.
ssGetDWorkComplexSignal Determine whether the elements of a
data type work vector are real or complex
numbers.
ssGetDWorkDataType Get the data type of a data type work vector.
ssGetDWorkName Get the name of a data type work vector.
ssGetDWorkUsedAsDState Determine whether a data type work vector
is used as a discrete state vector.
ssGetDWorkWidth Get the size of a data type work vector.
ssGetdX Get the derivatives of the continuous states
of an S-function.
ssGetIWork Get an S-functions integer-valued (int_T)
work vector.
ssGetIWorkValue Get a value from a blocks integer work
vector.
ssGetModeVector Get an S-functions mode work vector.
ssGetModeVectorValue Get an element of a blocks mode vector.
ssGetNonsampledZCs Get an S-functions zero-crossing signals
vector.
ssGetNumContStates Determine the number of continuous states
that an S-function has.
9-17
9 SimStruct Functions By Category
State and Work Vector (Continued)
Macro Description
ssGetNumDiscStates Determine the number of discrete states
that an S-function has.
ssGetNumDWork Get the number of data type work vectors
used by a block.
ssGetNumIWork Get the size of an S-functions integer work
vector.
ssGetNumModes Determine the size of an S-functions mode
vector.
ssGetNumNonsampledZCs Determine the number of nonsampled zero
crossings that an S-function detects.
ssGetNumPWork Determine the size of an S-functions pointer
work vector.
ssGetNumRWork Determine the size of an S-functions
real-valued (real_T) work vector.
ssGetPWork Get an S-functions pointer (void *) work
vector.
ssGetPWorkValue Get a pointer from a pointer work vector.
ssGetRealDiscStates Get the real (real_T) values of an
S-functions discrete state vector.
ssGetRWork Get an S-functions real-valued (real_T)
work vector.
ssGetRWorkValue Get an element of an S-functions real-valued
work vector.
ssSetDWorkComplexSignal Specify whether the elements of a data type
work vector are real or complex.
ssSetDWorkDataType Specify the data type of a data type work
vector.
ssSetDWorkName Specify the name of a data type work vector.
9-18
SimStruct Macros and Functions Listed by Usage
State and Work Vector (Continued)
Macro Description
ssSetDWorkUsedAsDState Specify that a data type work vector is used
as a discrete state vector.
ssSetDWorkWidth Specify the width of a data type work vector.
ssSetIWorkValue Set an element of a blocks integer work
vector.
ssSetModeVectorValue Set an element of a blocks mode vector.
ssSetNumContStates Specify the number of continuous states that
an S-function has.
ssSetNumDiscStates Specify the number of discrete states that
an S-function has.
ssSetNumDWork Specify the number of data type work vectors
used by a block.
ssSetNumIWork Specify the size of an S-functions integer
(int_T) work vector.
ssSetNumModes Specify the number of operating modes that
an S-function has.
ssSetNumNonsampledZCs Specify the number of zero crossings that an
S-function detects.
ssSetNumPWork Specify the size of an S-functions pointer
(void *) work vector.
ssSetNumRWork Specify the size of an S-functions real
(real_T) work vector.
9-19
9 SimStruct Functions By Category
State and Work Vector (Continued)
Macro Description
ssSetPWorkValue Set an element of a blocks pointer work
vector.
ssSetRWorkValue Set an element of a blocks floating-point
work vector.
Miscellaneous
Macro Description
ssCallExternalModeFcn Invoke the external mode function for an
S-function.
ssGetModelName Get the name of an S-Function block or model
containing the S-function.
ssGetParentSS Get the parent of an S-function.
ssGetPath Get the path of an S-function or the model
containing the S-function.
ssGetRootSS Return the root (model) SimStruct.
ssGetUserData Access user data.
ssSetExternalModeFcn Specify the external mode function for an
S-function.
ssSetOptions Set various simulation options.
9-20
SimStruct Macros and Functions Listed by Usage
Miscellaneous (Continued)
Macro Description
ssSetPlacementGroup Specify the execution order of a sink or source
S-function.
ssSetUserData Specify user data.
Real-Time Workshop
Macro Description
ssGetDWorkRTWIdentifier Get the identifier used to declare a
DWork vector in code generated from
the associated S-function.
ssGetDWorkRTWStorageClass Get the storage class of a DWork vector
in code generated from the associated
S-function.
ssGetDWorkRTWTypeQualifier Get the C type qualifier (e.g., const)
used to declare a DWork vector in
code generated from the associated
S-function.
ssGetPlacementGroup Get the name of the placement group
of a block.
ssSetDWorkRTWIdentifier Set the identifier used to declare a
DWork vector in code generated from
the associated S-function.
ssSetDWorkRTWStorageClass Set the storage class of a DWork vector
in code generated from the associated
S-function.
ssSetDWorkRTWTypeQualifier Set the C type qualifier (e.g., const)
used to declare a DWork vector in
code generated from the associated
S-function.
ssSetPlacementGroup Specify the name of the placement
group of a block.
9-21
9 SimStruct Functions By Category
Real-Time Workshop (Continued)
Macro Description
ssWriteRTW2dMatParam Write a Simulink matrix parameter to
the S-functions model.rtw file.
ssWriteRTWMx2dMatParam Write a MATLAB matrix parameter to
the S-functions model.rtw file.
ssWriteRTWMxVectParam Write a MATLAB vector parameter to
the S-functions model.rtw file.
ssWriteRTWParameters Write tunable parameters to the
S-functions model.rtw file.
ssWriteRTWParamSettings Write settings for the S-functions
parameters to the model.rtw file.
ssWriteRTWScalarParam Write a scalar parameter to the
S-functions model.rtw file.
ssWriteRTWStr Write a string to the S-functions
model.rtw file.
ssWriteRTWStrParam Write a string parameter to the
S-functions model.rtw file.
ssWriteRTWStrVectParam Write a string vector parameter to the
S-functions model.rtw file.
ssWriteRTWVectParam Write a Simulink vector parameter to
the S-functions model.rtw file.
ssWriteRTWWorkVect Write the S-functions work vectors to
the model.rtw file.
9-22
10
S-Function Options
Alphabetical List
This section describes the S-function options available through
ssSetOptions. Each S-function sets its applicable options at the end of its
mdlInitializeSizes method. Use the OR operator (|) to set multiple options.
For example:
ssSetOptions(S, SS_OPTION_EXCEPTION_FREE_CODE |
SS_OPTION_DISCRETE_VALUED_OUTPUT);
SS_OPTION_ALLOW_CONSTANT_PORT_SAMPLE_TIME
Purpose Allow constant sample time for a port
Description Allows an S-function with port-based sample times to specify or inherit
constant sample times. Setting this option tells Simulink that all
input and output ports support constant sample times. See Specifying
Constant Sample Time for a Port on page 7-33 for more information.
Example See sfun_port_constant.c, the source file for the
sfcndemo_port_constant.mdl demo, for an example.
See Also SS_OPTION_DISALLOW_CONSTANT_SAMPLE_TIME
10-2
SS_OPTION_ALLOW_INPUT_SCALAR_EXPANSION
Purpose Allow scalar expansion of input ports
Description Specifies that the input to your S-function input ports can be have a
width of either 1 or the size specified by the port, usually referred to
as the block width. The S-function expands scalar inputs to the same
dimensions as the block width. See Scalar Expansion of Inputs on
page 7-21 for more information.
Example See sfun_multiport.c, the source file for the
sfcndemo_sfun_multiport.mdl demo, for an example.
10-3
SS_OPTION_ALLOW_PARTIAL_DIMENSIONS_CALL
Purpose Allow calls to mdlSetInputPortDimensionInfo and
mdlSetOutputPortDimensionInfo with partial dimension
information
Description Indicates the S-function can handle dynamically dimensioned signals.
By default, Simulink calls the mdlSetInputPortDimensionInfo
or mdlSetOutputPortDimensionInfo methods if the number of
dimensions and size of each dimension for the candidate port are
fully known. If SS_OPTION_ALLOW_PARTIAL_DIMENSIONS_CALLS is
set, Simulink may also call these methods with partial dimension
information. For example, the methods may be called when the port
width is known, but the actual 2-D dimensions are unknown. See
mdlSetDefaultPortDimensionInfo for more information.
See Also mdlSetDefaultPortDimensionInfo
10-4
SS_OPTION_ALLOW_PORT_SAMPLE_TIME_IN_TRIGSS
Purpose Allow an S-function with port-based sample times to operate in a
triggered subsystem
Description Allows an S-function that uses port-based sample times to operate in a
triggered subsystem. During sample time propagation, use the macro
ssSampleAndOffsetAreTriggered to determine if the sample and
offset times correspond to the block being in a triggered subsystem. If
the block is triggered, all port sample times must be either triggered
or constant. See Configuring Port-Based Sample Times for Use in
Triggered Subsystems on page 7-34 for more information.
Example See sfun_port_triggered.c, the source file for the
sfcndemo_port_triggered.mdl demo, for an example.
See Also ssSampleAndOffsetAreTriggered
10-5
SS_OPTION_ASYNC_RATE_TRANSITION
Purpose Create a read-write pair of blocks that ensure correct data transfer
Description Creates a read-write pair of blocks intended to guarantee correct data
transfers between a synchronously (periodic) and an asynchronously
executing subsystem or between two asynchronously executing
subsystems. Both the read S-function and write S-function should set
this option.
An asynchronously executed function-call subsystem is a function-call
subsystem driven by an S-function with the SS_OPTION_ASYNCHRONOUS
specified.
Simulink defines two classes of asynchronous rate transitions.
Read-write pairs. In this class, two blocks, using a technique such as
double buffering, ensure data integrity in a multitasking environment.
When creating the read-write pair of blocks, the S-functions for these
blocks should set the SS_OPTION_ASYNC_RATE_TRANSITION option.
Furthermore, the MaskType property of the read block, must include
the string read and the MaskType property of write block must
include the string write.
A single protected or unprotected block. To create a single Protected
Rate Transition block, create a subsystem that contains the following
and set the Tag value of the Outport block to AsyncRateTransition.
The S-function then provides the code for the protected
transition. Note, this S-function does not set the
SS_OPTION_ASYNC_RATE_TRANSITION option.
See Also SS_OPTION_ASYNCHRONOUS
10-6
SS_OPTION_ASYNCHRONOUS
Purpose Specify this S-function drives a function-call subsystem attached to
interrupt service routines
Description Specifies that the S-function is driving function-call subsystems
attached to interrupt service routines. This option applies only to
S-functions that have no input ports during code generation and 1
output port. During simulation, the S-function may have an input
port to provide a condition on which to execute. The output port must
be configured to perform function calls on every element. If any of
these requirements is not met, the SS_OPTION_ASYNCHRONOUS option
is ignored. Specifying this option
Informs Simulink that there is no implied data dependency involving
the data sources or destinations of the function-call subsystem called
by the S-function.
Causes the function-call subsystem attached to the S-function to be
colored cyan, indicating that it does not execute at a periodic rate.
Enables additional checks to verify that the model is constructed
correctly.
a Simulink validates that the appropriate asynchronous rate
transition blocks reside between the cyan function-call subsystem.
Simulink also checks that period tasks exists. You can directly
read and write from the function-call subsystem by using a
block that has no computational overhead. To ensure safe task
transitions between period and asynchronous tasks, use the
SS_OPTION_ASYNC_RATE_TRANSITION option.
b For data transfers between two asynchronously executed (cyan)
function-call subsystem, Simulink validates that the appropriate
asynchronous task transition blocks exits.
See Also SS_OPTION_ASYNC_RATE_TRANSITION
10-7
SS_OPTION_CALL_TERMINATE_ON_EXIT
Purpose Force call to mdlTerminate
Description Guarantees Simulink will call the S-functions mdlTerminate method
before destroying a block that references the S-function. Calling
mdlTerminate allows your S-function to clean up after itself, for
example, by freeing memory it allocated during a simulation. Simulink
destroys an S-function block under the following circumstances.
1 A simulation ends either normally or as a result of invoking
ssSetErrorStatus.
2 A user deletes the block.
3 Simulink eliminates the block as part of a block reduction
optimization (see Block reduction).
If this option is not set, Simulink calls your S-functions mdlTerminate
method only if the mdlStart method of at least one block in the model
containing the S-function executed without error.
See Also mdlTerminate
10-8
SS_OPTION_CAN_BE_CALLED_CONDITIONALLY
Purpose Specify this S-function can be called conditionally
Description Specifies that the S-function can be called conditionally by other
blocks. Simulink uses this option to determine if the S-Function block
can be moved into the execution context of the conditionally executed
subsystem in which the S-function resides. See Conditional Execution
Behavior in Using Simulink for more information.
10-9
SS_OPTION_DISALLOW_CONSTANT_SAMPLE_TIME
Purpose Disallow constant sample time inheritance
Description Prohibits the S-Function block that references this
S-function from inheriting a constant sample time. The
SS_OPTION_DISALLOW_CONSTANT_SAMPLE_TIME option applies only to
S-functions that use block-based sample times.
Note If the S-function declares the number of sample times as
PORT_BASED_SAMPLE_TIMES it will not inherit a constant sample time
unless it specifies the SS_OPTION_ALLOW_CONSTANT_PORT_SAMPLE_TIME
option.
If the S-function specifies this option and inherits a constant sample
time, i.e., a sample time of inf, Real-Time Workshop may not generate
code for the corresponding S-function block. Real-Time Workshop
determines how to generate code for the block based on if the block
is invariant.
A block is invariant if all of its port signals are invariant. A signal
is invariant if it has a constant value during the entire simulation.
However, a constant block sample time does not guarantee all the
blocks signals are invariant. See Inlining Invariant Signals in the
Real-Time Workshop Users Guide for more information.
If the block is not invariant, Real-Time Workshop generates code only
in the model_initialize function. If the block is invariant, Real-Time
Workshop eliminates the blocks code altogether.
Example See matlabroot/simulink/src/sfblk_manswitch.c for an example.
See Also SS_OPTION_ALLOW_CONSTANT_PORT_SAMPLE_TIME
10-10
SS_OPTION_DISCRETE_VALUED_OUTPUT
Purpose Specify this S-function has discrete valued output
Description Specifies this S-function has discrete valued outputs. With this option
set, Simulink does not assign algebraic variables to this S-function
when it appears in an algebraic loop.
10-11
SS_OPTION_EXCEPTION_FREE_CODE
Purpose Improve performance of exception-free S-functions
Description Improves performance of S-functions that do not use mexErrMsgTxt,
mxCalloc, or any other routines that can throw an exception. An
S-function is not exception free if it contains any routine that, when
called, has the potential of long-jumping out of a block of code and
into another scope. See Exception Free Code on page 7-60 for more
information.
See Also SS_OPTION_RUNTIME_EXCEPTION_FREE_CODE
10-12
SS_OPTION_FORCE_NONINLINED_FCNCALL
Purpose Specify generated code format for function-call subsystems called by
this S-function
Description Indicates that Real-Time Workshop should generate procedures for
all function-call subsystems called by this S-function, instead of
possibly inlining the subsystems code. If an S-function sets this option,
Real-Time Workshop ignores the Inline setting for the Real-Time
Workshop system code option on the subsystems Block Parameters
dialog box. See Nonvirtual Subsystem Code Generation in the
Real-Time Workshop Users Guide for more information.
10-13
SS_OPTION_NONVOLATILE
Purpose Enable Simulink to remove unnecessary S-Function blocks
Description Specifies this S-function has no side effects. Setting this option enables
Simulink to remove the S-Function block referencing this S-function
during dead branch elimination, if it is not needed.
10-14
SS_OPTION_PLACE_ASAP
Purpose Specify this S-function should be placed as soon as possible
Description Specifies that this S-function should be placed as soon as possible. This
option is typically used by devices connecting to hardware.
10-15
SS_OPTION_PORT_SAMPLE_TIMES_ASSIGNED
Purpose Specify this S-function uses port-based sample times
Description Indicates the S-function registers multiple sample times
(ssSetNumSampleTimes > 1) to specify the rate at which each input and
output port is running. The simulation engine needs this information
when checking for illegal rate transitions. If an S-function uses this
option, it cannot inherit its sample times. See Hybrid Block-Based and
Port-Based Sample Times on page 7-36 for more information.
Example See matlabroot/simulink/src/mixedm.c for an example.
10-16
SS_OPTION_REQ_INPUT_SAMPLE_TIME_MATCH
Purpose Specify sample times of input signal and port must match
Description Specifies that the input signal sample times must match the sample
time assigned to the block input port. For example:
generates an error if this option is set. Simulink does not generate an
error if the block or input port sample time is inherited.
10-17
SS_OPTION_RUNTIME_EXCEPTION_FREE_CODE
Purpose Improve performance of run-time exception-free S-functions
Description Improves performance of S-functions that do not use mexErrMsgTxt,
mxCalloc, or any other routines that can throw an exception
inside of a run-time routines. Applicable run-time routines
include mdlGetTimeOfNextVarHit, mdlOutputs, mdlUpdate, and
mdlDerivatives.
See Also SS_OPTION_EXCEPTION_FREE_CODE
10-18
SS_OPTION_SIM_VIEWING_DEVICE
Purpose Indicate S-Function block is a SimViewingDevice
Description Indicates the S-Function block referencing this S-function is a
SimViewingDevice. As long as the block meets the other requirements
for a SimViewingDevice, i.e., no states, no outputs, etc., Simulink
considers the block to be an external mode block. As an external model
block, the block appears in the external mode GUI and Simulink does
not generate code for it. During an external mode simulation, Simulink
runs the block only on the host. See Sim Viewing Devices in External
Mode on page 7-55 in Writing S-Functions for more information.
10-19
SS_OPTION_SFUNCTION_INLINED_FOR_RTW
Purpose Specify use of TLC-file during code generation
Description Indicates the S-function has an associated TLC-file and does not
contain an mdlRTW method. Setting this option has no effect if the
S-function contains an mdlRTW method. During code generation,
if SS_OPTION_SFUNCTION_INLINED_FOR_RTW is set and Real-Time
Workshop cannot locate the S-functions TLC-file, Real-Time Workshop
generates an error. If SS_OPTION_SFUNCTION_INLINED_FOR_RTW is not
set but Real-Time Workshop does locate a TLC-file for the S-function,
it uses the TLC-file.
10-20
SS_OPTION_SUPPORTS_ALIAS_DATA_TYPES
Purpose Support data type aliases
Description Specifies how the S-function handles signals whose data types are
aliases (see Simulink.Aliastype for more information about data type
aliases). If this option is set and the S-functions inputs and outputs use
data type aliases, SimStruct macros such as ssGetInputPortDataType
and ssGetOutputPortDataType return the data type IDs of those
aliases. However, if this option is not set, the SimStruct macros
return the data type IDs associated with the equivalent built-in data
types instead. For a list of built-in values for the data type ID, see
ssGetInputPortDataType.
Note If this option is not set and the S-functions inputs use data type
aliases, Simulink attempts to propagate the aliases to the S-functions
outputs. However, this process can fail, in which case Simulink
propagates the equivalent built-in data types instead. To explicitly
control the propagation of data type aliases through an S-function,
enable the SS_OPTION_SUPPORTS_ALIAS_DATA_TYPES option.
10-21
SS_OPTION_USE_TLC_WITH_ACCELERATOR
Purpose Use TLC-file when simulating in accelerated mode
Description Forces the Accelerator mode in Simulink to use the TLC inlining code
for the S-function, which speeds up execution of the S-function. If
this option is not set, the Accelerator mode uses the MEX version
of the S-function even if a TLC-file for the S-function exists. This
option should not be set for device driver blocks (A/D) or when
there is an incompatibility between running the MEX mdlStart or
mdlInitializeConditions functions together with the TLC Outputs,
Update, or Derivatives functions. Also, this option indicates that the
TLC inlining code should be used when generating a simulation target
for a reference submodel that contains this S-function.
Note The Accelerator mode in Simulink does not require the Real-Time
Workshop to run an inlined S-function. However, to ensure that the
inlined S-function can run in accelerated mode in current and future
Simulink releases, the TLC-file for the S-function must use documented
TLC functions to access the CompiledModel structure.
10-22
SS_OPTION_WORKS_WITH_CODE_REUSE
Purpose Specify this S-function supports code reuse
Description Signifies that this S-function is compatible with the subsystem code
reuse feature of Real-Time Workshop. See Writing S-Functions That
Support Code Reuse in the "Real-Time Workshop Users Guide" for
more information. If this option is not set, Real-Time Workshop will not
reuse any subsystem containing this S-Function.
10-23
SS_OPTION_WORKS_WITH_CODE_REUSE
10-24
A
Examples
Use this list to find examples in the documentation.
A Examples
S-Function Features
Passing Parameters to S-Functions on page 1-5
Multirate S-Function Blocks on page 7-37
Example Involving a Pointer Work Vector on page 7-47
S-Function Examples
S-Function Examples on page 1-20
Continuous States on page 7-63
Discrete States on page 7-70
Continuous and Discrete States on page 7-77
Variable Sample Time on page 7-84
Array Inputs and Outputs on page 7-90
Zero-Crossing Detection on page 7-102
Discontinuities in Continuous States on page 7-119
S-Function Builder
Building S-Functions Automatically on page 3-6
Library/Object/Source files on page 3-24
Enable access to SimStruct on page 3-35
Writing S-Functions in C
Example of a Basic C MEX S-Function on page 3-41
Example of Integrating Existing C Functions into Simulink Models with
the Legacy Code Tool on page 3-56
Creating C++ S-Functions
Source File Format on page 4-2
A-2
Creating Ada S-Functions
Creating Ada S-Functions
Ada S-Function Specification on page 5-4
Ada S-Function Body on page 5-5
Example of an Ada S-Function on page 5-12
Creating Fortran S-Functions
Example of a Level 1 Fortran S-Function on page 6-3
Example C MEX S-Function Calling Fortran Code on page 6-16
A-3
A Examples
A-4
Index
Index A
Ada S-functions
creating 5-4
example 5-12
GNAT Ada95 compiler 5-11
mex syntax 5-11
source file format 5-4
specification 5-4
additional parameters for M-file S-functions 2-13
array bounds
checking 7-62
B
block I/O ports 7-16
block-based sample times 7-27
specifying 7-27
Build Info pane
S-Function Builder 3-33
C
C functions
integrating into Simulink models 3-53
example 3-56
C language header file
matlabroot/simulink/include/-
simstruc.h 9-2
C MEX S-functions
advantages 3-3
converting from level 1 to level 2 3-89
creating 3-4
definition 1-2
deploying S-functions generated with 3-72
example 3-41
generating and compiling with Legacy Code
Tool 3-69
modes for compiling 3-51
S-Function Builder 3-6
Simulink interaction 3-74
C++ objects
making persistent 4-6
C++ S-functions
building 4-8
mex command 4-8
C-to-Fortran gateway S-function 6-8
callback methods 1-11
CFortran 6-13
cg_sfun.h 3-50
checking array bounds 7-62
compile option
for legacy_code function 3-69
compiler compatibility
Fortran 6-9
continuous blocks
setting sample time 7-38
Continuous Derivatives pane
S-Function Builder 3-29
continuous state S-function example (C
MEX) 7-63
Converting Level-1 M-file S-functions 2-13
creating persistent C++ objects 4-6
D
data structures
Legacy Code Tool
registering 3-60
registering multiple 3-71
data types
supported by Legacy Code Tool 3-67
using user-defined 7-24
demos
Legacy Code Tool 3-72
device drivers
integrating into Simulink models 3-53
direct feedthrough 1-14
discrete state S-function example (C MEX) 7-70
Discrete Update pane
S-Function Builder 3-31
Index-1
Index
dynamically sized inputs 1-15
E
error handling
checking array bounds 7-62
exception free code 7-59
examples
Ada S-function specification 5-4
C MEX S-function 3-41
continuous state S-function (C MEX) 7-63
discrete state S-function (C MEX) 7-70
Fortran MEX S-function 6-3
hybrid system S-function (C MEX) 7-77
integrating C functions into Simulink
models 3-56
Legacy Code Tool 3-56
legacy_code function 3-56
matrix support S-function (C MEX) 7-90
pointer work vector 7-47
sample time for continuous block 7-38
sample time for hybrid block 7-38
time-varying continuous transfer function (C
MEX) 7-119
variable-step S-function (C MEX) 7-84
zero-crossing S-function (C MEX) 7-102
exception free code 7-60
extern "C" statement 4-2
F
Fortran compilers 6-13
Fortran math library 6-11
Fortran MEX S-functions
example 6-3
template file 6-3
frame-based signals, implementing in
S-functions 7-56
function specifications
Legacy Code Tool
declaring 3-62
function-call subsystems 7-50
functions
Legacy Code Tool specifications for 3-62
H
header files 3-49
hybrid blocks
setting sample time 7-38
hybrid sample times
specifying 7-36
hybrid system S-function example (C MEX) 7-77
I
Initialization pane
S-Function Builder 3-14
InitializeConditionsFcnSpec field
in Legacy Code Tool data structure 3-62
input ports
how to create 7-16
inputs, dynamically sized 1-15
integration
of C functions into Simulink models 3-53
example 3-56
L
Legacy Code Tool
data structures
initialization 3-60
registering 3-60
registering multiple 3-71
declaring function specifications 3-62
demos 3-72
deploying S-functions generated with 3-72
generating and compiling S-functions
with 3-69
Index-2
Index
integrating C functions into Simulink models
with 3-53
example 3-56
limitations 3-73
overview 3-53
supported data types 3-67
legacy_code function
example 3-56
generating file for code generation
support 3-71
level 1 C MEX S-functions
converting to level 2 3-89
Libraries pane
S-Function Builder 3-23
limitations
Legacy Code Tool 3-73
lookup tables
integrating into Simulink models 3-53
M
M-file S-functions
arguments 2-10
creating 2-9
defining characteristics 2-12
definition 2-9
passing additional parameters 2-13
routines 2-9
masked multiport S-functions 7-23
masked S-function blocks
for calling S-function generated with Legacy
Code Tool 3-70
matlabroot/simulink/include/simstruc.h C
language header file 9-2
matlabroot/simulink/src/csfunc.c example
file 7-64
matlabroot/simulink/src/dsfunc.c example
file 7-71
matlabroot/simulink/src/mixedm.c example
file 7-77
matlabroot/simulink/src/sfun_counter_-
cpp.cpp
ensuring Simulink compatibility of C++
S-functions 4-2
matlabroot/simulink/src/sfun_matadd.c
example file 7-91
matlabroot/simulink/src/sfun_timestwo_for.F
Fortran example file 6-3
matlabroot/simulink/src/sfun_zc_sat.c
example file 7-102
matlabroot/simulink/src/stvctf.c example
file 7-119
matlabroot/simulink/src/vsfunc.c example
file 7-84
matrix support S-function example (C MEX) 7-90
matrix.h 3-49
mdlCheckParameters 8-2
mdlDerivatives 8-5
mdlGetTimeOfNextVarHit 8-9
mdlInitializeConditions 8-11
mdlInitializeSampleTimes 8-14
mdlInitializeSizes 8-19
and sizes structure 1-15
calling sizes 2-12
mdlOutputs 8-25
mdlProcessParameters 8-27
mdlRTW 8-36
mdlSetDefaultPortComplexSignals 8-38
mdlSetDefaultPortDataTypes 8-39
mdlSetDefaultPortDimensionInfo 8-41
mdlSetInputPortComplexSignal 8-43
mdlSetInputPortDataType 8-45
mdlSetInputPortDimensionInfo 8-47
mdlSetInputPortFrameData 8-49
mdlSetInputPortSampleTime 8-51
mdlSetInputPortWidth 8-54
mdlSetOutputPortComplexSignal 8-55
mdlSetOutputPortDataType 8-57
mdlSetOutputPortDimensionInfo 8-59
mdlSetOutputPortSampleTime 8-61
Index-3
Index
mdlSetOutputPortWidth 8-63
mdlSetWorkWidths 8-64
mdlSimStatusChange 8-66
mdlStart 8-68
mdlTerminate 8-69
mdlUpdate 8-71
mdlZeroCrossings 8-74
memory allocation 7-49
memory and work vectors 7-42
mex command
building Ada S-functions 5-11
building C MEX S-functions 3-47
building C++ S-functions 4-8
MEX S-functions
deploying S-functions generated with 3-72
generating and compiling with Legacy Code
Tool 3-69
mex.h 3-49
multirate S-Function blocks 7-37
synchronizing 7-39
O
obsolete macros 3-92
output ports
how to create 7-20
OutputFcnSpec field
in Legacy Code Tool data structure 3-62
Outputs pane
S-Function Builder 3-25
P
parameters
M-file S-functions 2-13
passing to S-functions 1-5
run-time parameters 7-7
tunable parameters 7-4
penddemo demo 1-6
persistence
C++ objects 4-6
port-based sample times 7-31
constant 7-33
inherited 7-32
specifying 7-31
triggered 7-34
R
reentrancy 7-42
run-time parameter names, uniqueness of 7-8
run-time parameters 7-7
run-time routines 7-61
S
S-function blocks
masked
for S-functions generated with Legacy
Code Tool 3-70
S-Function blocks
multirate 7-37
S-functions parameters field 7-2
synchronizing multirate 7-39
S-Function Builder
Build Info pane 3-33
Continuous Derivatives pane 3-29
customizing 3-11
Discrete Update pane 3-31
for C MEX S-functions 3-6
Initialization pane 3-14
Libraries pane 3-23
Outputs pane 3-25
setting the include path 3-24
S-function data types 3-51
S-function routines
M-file 2-9
S_FUNCTION_LEVEL 2, #define 3-48
S_FUNCTION_NAME, #define 3-48
S-functions 2-9 3-3 4-1 5-2 6-3
Index-4
Index
building C++ 4-8
C MEX 1-2
creating Ada 5-4
creating C MEX 3-4
creating Fortran 6-3
creating level 2 with Fortran 6-8
creating persistent C++ objects 4-6
creating run-time parameters 7-8
definition 1-2
deploying 3-72
direct feedthrough 1-14
exception free code 7-60
generating and compiling with Legacy Code
Tool 3-69
level 1 and level 2 6-2
masked multiport 7-23
purpose 1-6
routines 1-9
run-time parameters 7-7
run-time routines 7-61
using in models 1-3
when to use 1-6
writing in C++ 4-2
See also Ada S-functions; C MEX S-functions;
C++ S-functions; Fortran MEX S-functions;
M-file S-functions
S-functions parameters field
S-Function block 7-2
sample times
block-based 7-27
continuous block example 7-38
function behavior 7-26
hybrid block example 7-38
port-based 7-31
specifying block-based 7-27
specifying hybrid 7-36
specifying port-based 7-31
scalar expansion of inputs 7-21
sfcn_cmex_generate option
for legacy_code function 3-69
sfuntmpl.c template 3-48
sfuntmpl_fortran.F template 6-3
sfuntmpl.m template
M-file S-function 2-9
simsizes function
M-file S-function 2-12
SimStruct 3-51
SimStruct macros 9-3
simulation loop 1-8
simulation stages 1-8
simulink.c 3-50
sizes structure
fields
M-file S-function 2-12
returned in mdlInitializeSizes 1-15
slblock_generate option
for legacy_code function 3-70
SS_OPTION_ALLOW_CONSTANT_PORT_SAMPLE_TIME 10-2
SS_OPTION_ALLOW_INPUT_SCALAR_EXPANSION 10-3
SS_OPTION_ALLOW_PARTIAL_DIMENSIONS_CALL 10-4
SS_OPTION_ALLOW_PORT_SAMPLE_TIME_IN_TRIGSS 10-5
SS_OPTION_ASYNC_RATE_TRANSITION 10-6
SS_OPTION_ASYNCHRONOUS 10-7
SS_OPTION_CALL_TERMINATE_ON_EXIT 10-8
SS_OPTION_CAN_BE_CALLED_CONDITIONALLY 10-9
SS_OPTION_DISALLOW_CONSTANT_SAMPLE_TIME 10-10
SS_OPTION_DISCRETE_VALUED_OUTPUT 10-11
SS_OPTION_EXCEPTION_FREE_CODE 10-12
SS_OPTION_FORCE_NONINLINED_FCNCALL 10-13
SS_OPTION_NONVOLATILE 10-14
SS_OPTION_PLACE_ASAP 10-15
SS_OPTION_PORT_SAMPLE_TIMES_ASSIGNED 10-16
SS_OPTION_REQ_INPUT_SAMPLE_TIME_MATCH 10-17
SS_OPTION_RUNTIME_EXCEPTION_FREE_CODE 10-18
SS_OPTION_SFUNCTION_INLINED_FOR_RTW 10-20
SS_OPTION_SIM_VIEWING_DEVICE 10-19
SS_OPTION_SUPPORTS_ALIAS_DATA_TYPES 10-21
SS_OPTION_USE_TLC_WITH_ACCELERATOR 10-22
SS_OPTION_WORKS_WITH_CODE_REUSE 10-23
ssGetModeVectorValue 9-17
Index-5
Index
StartFcnSpec field
in Legacy Code Tool data structure 3-62
synchronizing multirate S-Function blocks 7-39
T
templates
M-file S-function 2-9
TerminateFcnSpec field
in Legacy Code Tool data structure 3-62
time-varying continuous transfer function
example (C MEX) 7-119
TLC block file
generating for C MEX S-functions 3-71
tmwtypes.h 3-49
tunable parameters 7-4
V
variable-step S-function example (C MEX) 7-84
W
work vectors 7-42
writing S-functions in Ada 5-4
writing S-functions in C++ 4-2
writing S-functions in MATLAB 2-9
Z
zero-crossing S-function example (C MEX) 7-102
Index-6