| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → Real-Time Workshop |
| Contents | Index |
| Learn more about Real-Time Workshop |
S-functions are an important class of target for which the Real-Time Workshop product can generate code. The ability to encapsulate a subsystem into an S-function allows you to increase its execution efficiency and facilitate code reuse.
The following sections describe the properties of S-function targets and demonstrate how to generate them. For more details on the structure of S-functions, see the Simulink Writing S-Functions documentation.
Using the S-function target, you can build an S-function component and use it as an S-Function block in another model. The S-function code format used by the S-function target generates code that conforms to the Simulink C MEX S-function application programming interface (API). Applications of this format include
Conversion of a model to a component. You can generate an S-Function block for a model, m1. Then, you can place the generated S-Function block in another model, m2. Regenerating code for m2 does not require regenerating code for m1.
Conversion of a subsystem to a component. By extracting a subsystem to a separate model and generating an S-Function block from that model, you can create a reusable component from the subsystem. See Creating an S-Function Block from a Subsystem for an example of this procedure.
Speeding up simulation. In many cases, an S-function generated from a model performs more efficiently than the original model.
Code reuse. You can incorporate multiple instances of one model inside another without replicating the code for each instance. Each instance will continue to maintain its own unique data.
The S-function target generates noninlined S-functions. Within the same release, you can generate an executable from a model that contains generated S-functions by using the generic real-time or real-time malloc targets. This is not supported when incorporating a generated S-function from one release into a model that you build with a different release.
You can place a generated S-Function block into another model from which you can generate another S-function format. This allows any level of nested S-functions.
You should avoid nesting S-functions in a model or subsystem having the same name as the S-function (possibly several levels apart). In such situations, the S-function can be called recursively. The Real-Time Workshop software currently does not detect such loops in S-function dependency, which can result in aborting or hanging your MATLAB session.
To prevent this from happening, you should be sure to name the subsystem or model to be generated as an S-function target uniquely, to avoid duplicating any existing MEX filenames on the MATLAB path.
Note While the S-function target provides a means to deploy an application component for reuse while shielding its internal logic from inspection and modification, the preferred solutions for protecting intellectual property in distributed components are:
|
To deploy your generated S-Function block for inclusion in other models for simulation, you need only provide the binary MEX-file object that was generated in the current working directory when the S-Function block was created:
| subsys_sf.mexext |
where subsys is the subsystem name and mexext is a platform-dependent MEX-file extension (see mexext). For example, SourceSubsys_sf.mexw32.
To deploy your generated S-Function block for inclusion in other models for code generation, you must provide all of the files that were generated in the current working directory when the S-Function block was created:
subsys_sf.c or .cpp, where subsys is the subsystem name (for example, SourceSubsys_sf.c)
subsys_sf.h
subsys_sf.mexext, where mexext is a platform-dependent MEX-file extension (see mexext)
Subdirectory subsys_sfcn_rtw and its contents
A generated S-Function block can inherit its sample time from the model in which it is placed if certain criteria are met. Conditions that govern sample time propagation for both Model blocks and generated S-Function blocks are described in Inheriting Sample Times in the Simulink documentation and Inherited Sample Time for Referenced Models in the Real-Time Workshop documentation.
To ensure that your generated S-Function block meets the criteria for inheriting sample time, you must constrain the solver for the model from which the S-Function block is generated. On the Solver configuration parameters dialog pane, set Type to Fixed-step and Periodic sample time constraint to Ensure sample time independent. If the model is unable to inherit sample times, this setting causes the Simulink software to display an error message when building the model. See Periodic sample time constraint in the Simulink documentation for more information about this option.
If the model containing the subsystem from which you generate an S-function uses a variable-step solver, the generated S-function contains zero-crossing functions and will work properly only in models that use variable-step solvers.
If the model containing the subsystem from which you generate an S-function uses a fixed-step solver, the generated S-function contains no zero-crossing functions and the generated S-function will work properly in models that use variable-step or fixed-step solvers.
This section demonstrates how to extract a subsystem from a model and generate a reusable S-function component from it.
The next figure shows SourceModel, a simple model that inputs signals to a subsystem. The subsequent figure shows the subsystem, SourceSubsys. The signals, which have different widths and sample times, are
A Step block with sample time 1
A Sine Wave block with sample time 0.5
A Constant block whose value is the vector [-2 3]
SourceModel

SourceSubsys

The objective is to extract SourceSubsys from the model and build an S-Function block from it, using the S-function target. The S-Function block must perform identically to the subsystem from which it was generated.
In this model, SourceSubsys inherits sample times and signal widths from its input signals. However, S-Function blocks created from a model using the S-function target will have all signal attributes (such as signal widths or sample times) hard-wired. (The sole exception to this rule concerns sample times, as described in Sample Time Propagation in Generated S-Functions.)
In this example, you want the S-Function block to retain the properties of SourceSubsys as it exists in SourceModel. Therefore, before you build the subsystem as a separate S-function component, you must set the inport sample times and widths explicitly. In addition, the solver parameters of the S-function component must be the same as those of the original model. This ensures that the generated S-function component will operate identically to the original subsystem (see Choice of Solver Type for an exception to this rule).
To build SourceSubsys as an S-function component,
Create a new model and copy/paste SourceSubsys into the empty window.
Set the signal widths and sample times of inports inside SourceSubsys such that they match those of the signals in the original model. Inport 1, Filter, has a width of 1 and a sample time of 1. Inport 2, Xferfcn, has a width of 1 and a sample time of 0.5. Inport 3, offsets, has a width of 2 and a sample time of 0.5.
The generated S-Function block should have three inports and one outport. Connect inports and an outport to SourceSubsys, as shown in the next figure.

The correct signal widths and sample times are propagated to these ports.
Set the solver type, mode, and other solver parameters such that they are identical to those of the source model. This is easiest to do if you use Model Explorer.
In Model Explorer or the Configuration Parameters dialog box, click the Real-Time Workshop tab.
In the System Target File Browser, select the S-function target, rtwsfcn.tlc, and click OK. The Real-Time Workshop pane appears as follows.

Select the Real-Time Workshop S-Function Code Generation Options tab (in Model Explorer) or pane (in the Configuration Parameters dialog box).
Make sure that Create New Model is selected, as shown in the next figure:

When this option is selected, the build process creates a new model after it builds the S-function component. The new model contains an S-Function block, linked to the S-function component.
Save the new model containing your subsystem, for example as SourceSubsys.mdl.
The Real-Time Workshop build process builds the S-function component in the working directory. After the build, a new model window is displayed.

Optionally you can save the generated model, for example as SourceSubsys_Sfunction.mdl.
You can now copy the Real-Time Workshop S-Function block from the new model and use it in other models or in a library.
Note For a list of files required to deploy your S-Function block for simulation or code generation, see Required Files for S-Function Deployment. |
The next figure shows the S-Function block plugged into the original model. Given identical input signals, the S-Function block will perform identically to the original subsystem.
Generated S-Function Configured Like SourceModel

The speed at which the S-Function block executes is typically faster than the original model. This difference in speed is more pronounced for larger and more complicated models. By using generated S-functions, you can increase the efficiency of your modeling process.
You can use tunable parameters in generated S-functions in two ways:
Use the Generate S-function feature (see Automated S-Function Generation).
or
Use the Model Parameter Configuration dialog box (see Parameter Considerations) to declare desired block parameters tunable.
Block parameters that are declared tunable with the auto storage class in the source model become tunable parameters of the generated S-function.
These parameters do not become part of a generated model_P (formerly rtP) parameter data structure, as they would in code generated from other targets. Instead, the generated code accesses these parameters by using MEX API calls such as mxGetPr or mxGetData. Your code should access these parameters in the same way.
For more information on MEX API calls, see Writing S-Functions in C in the Simulink Writing S-Functions documentation and External Interfaces in the MATLAB online documentation.
S-Function blocks created by using the S-function target are automatically masked. The mask displays each tunable parameter in an edit field. By default, the edit field displays the parameter by variable name, as in the following example.

You can choose to display the value of the parameter rather than its variable name by selecting Use Value for Tunable Parameters in the Options section.

When this option is chosen, the value of the variable (at code generation time) is displayed in the edit field, as in the following example.

The Generate S-function feature automates the process of generating an S-function from a subsystem. In addition, the Generate S-function feature presents a display of parameters used within the subsystem, and lets you declare selected parameters tunable.
As an example, consider SourceSubsys, the same subsystem illustrated in the previous example, Creating an S-Function Block from a Subsystem. The objective is to automatically extract SourceSubsys from the model and build an S-Function block from it, as in the previous example. In addition, the gain factor of the Gain block should be set within SourceSubsys to the workspace variable K (as illustrated in the next figure) and declare K as a tunable parameter.

To auto-generate an S-function from SourceSubsys with tunable parameter K,
Select Generate S-function from the Real-Time Workshop submenu of the Tools menu. This menu item is enabled when a subsystem is selected in the current model.
Alternatively, you can right-click the subsystem and select Real-Time Workshop > Generate S-Function from the subsystem block's context menu.
The Generate S-function window is displayed (see the next figure). This window shows all variables (or data objects) that are referenced as block parameters in the subsystem, and lets you declare them as tunable.
The upper pane of the window displays three columns:
Variable Name: name of the parameter.
Class: If the parameter is a workspace variable, its data type is shown. If the parameter is a data object, its name and class is shown
Tunable: Lets you select tunable parameters. To declare a parameter tunable, select the check box. In the next figure, the parameter K is declared tunable.
When you select a parameter in the upper pane, the lower pane shows all the blocks that reference the parameter, and the parent system of each such block.
Generate S-Function Window

If you have installed the Real-Time Workshop Embedded Coder product, and if the subsystem does not have a continuous sample time, the Create Real-Time Workshop Embedded Coder SIL block check box is available, as shown above. Otherwise, it is appears dimmed. When Create Real-Time Workshop Embedded Coder SIL block is selected, the build process generates a wrapper S-function by using the Real-Time Workshop Embedded Coder product. See Generating S-Function Wrappers in the Real-Time Workshop Embedded Coder documentation for more information.
After selecting tunable parameters, click the Build button. This initiates code generation and compilation of the S-function, using the S-function target. The Create New Model option is automatically enabled.
The build process displays status messages in the MATLAB Command Window. When the build completes, the tunable parameters window closes, and a new untitled model window opens.

The model window contains an S-Function block with the same name as the subsystem from which the block was generated (in this example, SourceSubsys). Optionally, you can save the generated model containing the generated block.
The generated code for the S-Function block is stored in the current working directory. The following files are written to the top level directory:
subsys_sf.c or .cpp, where subsys is the subsystem name (for example, SourceSubsys_sf.c)
subsys_sf.h
subsys_sf.mexext, where mexext is a platform-dependent MEX-file extension (for example, SourceSubsys_sf.mexw32)
The source code for the S-function is written to the subdirectory subsys_sfcn_rtw. The top-level .c or .cpp file is a stub file that simply contains an include directive that you can use to interface other C/C++ code to the generated code.
Note For a list of files required to deploy your S-Function block for simulation or code generation, see Required Files for S-Function Deployment. |
The generated S-Function block has inports and outports whose widths and sample times correspond to those of the original model.
The following code, from the mdlOutputs routine of the generated S-function code (in SourceSubsys_sf.c), shows how the tunable variable K is referenced by using calls to the MEX API.
static void mdlOutputs(SimStruct *S, int_T tid)
...
/* Gain: '<S1>/Gain' incorporates:
* Sum: '<S1>/Sum'
*/
rtb_Gain_n[0] = (rtb_Product_p + (*(((const
real_T**)ssGetInputPortSignalPtrs(S, 2))[0]))) * (*(real_T
*)(mxGetData(K(S))));
rtb_Gain_n[1] = (rtb_Product_p + (*(((const
real_T**)ssGetInputPortSignalPtrs(S, 2))[1]))) * (*(real_T
*)(mxGetData(K(S))));
Notes
|
This section lists the target file and template makefiles that are provided for use with the S-function target.
rtwsfcn.tlc
rtwsfcn_lcc.tmf — Lcc compiler
rtwsfcn_unix.tmf — The Open Group UNIX host
rtwsfcn_vc.tmf — Microsoft Visual C++ compiler
rtwsfcn_watc.tmf — Watcom C compiler
The Real-Time Workshop software creates a checksum for a Simulink model and uses the checksum during the build process for code reuse, model reference, and external mode features.
The Real-Time Workshop software calculates a model's checksum by
Calculating a checksum for each subsystem in the model. A subsystem's checksum is the combination of properties (data type, complexity, sample time, port dimensions, and so forth) of the subsystem's blocks.
Combining the subsystem checksums and other model-level information.
An S-function can add additional information, not captured during the block property analysis, to a checksum by calling the function ssSetChecksumVal. For the S-Function target, the value that gets added to the checksum is the checksum of the model or subsystem from which the S-function is generated.
The Real-Time Workshop software applies the subsystem and model checksums as follows:
Code reuse — If two subsystems in a model have the same checksum, the Real-Time Workshop build process generates code for one function only.
Model reference — If the current model checksum matches the checksum when the model was built, the Real-Time Workshop build process does not rebuild submodels.
External mode — If the current model checksum does not match the checksum of the code that is running on the target, the Real-Time Workshop build process generates an error.
Certain limitations apply to the use of tunable variables in expressions. When Real-Time Workshop software encounters an unsupported expression during code generation, a warning appears and the equivalent numeric value is generated in the code. For a list of the limitations, see Tunable Expression Limitations.
If you set the S-function upgrades needed option on the Diagnostics > Compatibility pane of the Configuration Parameters dialog box to warning or error, the Real-Time Workshop software reports that an upgrade is needed for any S-function you create with the Generate S-function feature. This is because the S-function target does not register run-time parameters. Run-time parameters are only supported for inlined S-Functions and the generated S-Function supports features that prevent it from being inlined (for example, it can call or contain other noninlined S-functions).
You can work around this limitation by setting the S-function upgrades needed option to none. Alternatively, if you have a Real-Time Workshop Embedded Coder license, select the Create Real-Time Workshop Embedded Coder SIL block check box on the Generate S-function for Subsystem dialog box and create a SIL block (containing the ERT S-function). In this case, you do not receive the upgrade messages. However, you cannot include SIL blocks inside other generated S-functions recursively.
When using the S-function target, the Real-Time Workshop code generator restricts I/O to correspond to the root model's Inport and Outport blocks (or the Inport and Outport blocks of the Subsystem block from which the S-function target was generated). No code is generated for Goto or From blocks.
To work around this restriction, create your model and subsystem with the required Inport and Outport blocks, instead of using Goto and From blocks to pass data between the root model and subsystem. In the model that incorporates the generated S-function, you would then add needed Goto and From blocks.
Example Before Work Around
Root model with a From block and subsystem, Subsystem1

Subsystem1 with a Goto block, which has global visibility and passes its input to the From block in the root model

Subsystem1 replaced with an S-function generated with the S-Function target — a warning results when you run the model because the generated S-function does not implement the Goto block

Example After Work Around
An Outport block replaces the GoTo block in Subsystem1. When you plug the generated S-function into the root model, its output connects directly to the To Workspace block.

The following limitations apply to building and updating S-functions using the Real-Time Workshop S-function target:
You cannot build models that contain Model blocks using the Real-Time Workshop S-function target. This also means that you cannot build a subsystem module by right-clicking (or by using Tools > Real-Time Workshop > Build subsystem) if the subsystem contains Model blocks. This restriction applies only to S-functions generated using the S-function target, not to ERT S-functions.
If you modify the model that generated an S-Function block, the Real-Time Workshop build process does not automatically rebuild models containing the generated S-Function block. This is in contrast to the practice of automatically rebuilding models referenced by Model blocks when they are modified (depending on the Model Reference Rebuild options configuration setting).
Handwritten S-functions without corresponding TLC files must contain exception-free code. For more information on exception-free code, see Exception Free Code in the Simulink Writing S-Functions documentation.
The S-function format does not support the following built-in blocks:
MATLAB Fcn block
S-Function blocks containing any of the following:
MATLAB language S-functions (unless you supply a TLC file for C code generation)
Fortran S-functions (unless you supply a TLC file for C code generation)
C/C++ MEX S-functions that call into the MATLAB environment
Scope block
To Workspace block
You can use SimState within C-MEX and Level-2 MATLAB language S-functions to save and restore the simulation state (see S-Function Compliance with the SimState in the Simulink documentation). However, SimState is not supported for code generation, including with the Real-Time Workshop S-function target.
Profiling the performance of generated code using the Target Language Compiler (TLC) hook function interface described in Profiling Code Performance is not supported for the S-function target.
![]() | Supporting Shared Utility Directories in the Build Process | Combining Multiple Models | ![]() |

Learn more about Simulink through this collection of videos, articles, technical literature and the Getting Started with Simulink Guide.
| © 1984-2010- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |