Main Content

Accelerate Simulation, Reuse Code, or Protect Intellectual Property by Using S-Function Target

S-functions are an important class of system target file for which the code generator can produce 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 illustrate how to generate them. For more details on the structure of S-functions, see C/C++ S-Function Basics.

About the S-Function Target

Using the S-function target, you can build an S-function component and use it as an S-Function block in another model. The following sections describe deployment considerations for the S-function target.

The 'S-Function' value for CodeFormat TLC variable 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 Create S-Function Blocks from a Subsystem for an example of this procedure.

  • Speeding up simulation. Often, 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 continues to maintain its own unique data.

You can place a generated S-function block into another model from which you can generate another S-function. This approach allows levels of nested S-functions. For limitations related to nesting, see Limitations on Nesting S-Functions.

Note

If you are generating code for a modeled software component, use a reference model instead of generating an S-function block from a subsystem.

Note

While you can use the S-function target 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:

Required Files for S-Function Deployment

There are different files required to deploy a generated S-Function block for simulation versus code generation.

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 folder when the S-Function block was created. The required file is:

  • subsys_sf.mexext

where subsys is the subsystem name and mexext is a platform-dependent MEX-file extension (see mexext). For example, SourceSubsys_sf.mexw64.

To deploy your generated S-Function block for inclusion in other models for code generation, provide the files that were generated in the current working folder when the S-Function block was created. The required files are:

  • 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)

  • Subfolder subsys_sfcn_rtw and its contents

The generated S-function code uses Configuration Parameters > Hardware Implementation parameter values that match the host system on which the function was built. When you use the S-function in a model for code generation, make sure that these parameter values for the model match the parameter values of the S-function.

Sample Time Propagation in Generated S-Functions

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 Referenced Model Sample Times and S-Functions That Specify Sample Time Inheritance Rules.

To generate an S-Function block that meets the criteria for inheriting sample time, you must constrain the solver for the model from which the S-Function block is generated. Set model configuration parameter 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. For more information about this option, see Periodic sample time constraint.

Choose a Solver Type

The table shows the possible combinations of top-level model solver types as these types relate to whether the model has discrete or continuous sample times and solver types for generated S-functions.

Top-Level Model Solver Options and Sample Times

 Model Configuration Parameters: Top-level model configuration
Sample TimesSolver Options, Type: Variable-stepSolver Options, Type: Fixed-step
DiscreteGenerated S-function requires a variable-step solverGenerated S-function can have a variable-step solver or a fixed-step solver
ContinuousGenerated S-function requires a variable-step solverGenerated S-function requires a fixed-step solver

S-functions generated from a subsystem have parameters that are hardcoded into the block. Simulink calculates parameters such as sample time when it generates the block, not during simulation run time. It is important to verify whether the generated S-Function block works as expected in the destination model.

Create S-Function Blocks from a Subsystem

This section shows 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 has 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 parameters of the original model. The generated S-function component operates identically to the original subsystem (see Choose a Solver Type for more information).

To build SourceSubsys as an S-function component,

  1. Create a new model and copy/paste the SourceSubsys block into the empty window.

  2. 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.

  3. 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 signal widths and sample times are propagated to these ports.

  4. 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.

  5. Set model configuration parameter System target file to rtwsfcn.tlc.

  6. Select the S-Function Target pane. 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.

    Click Apply.

  7. Save the new model containing your subsystem, for example as SourceSubsys.

  8. Build the model.

  9. The build process produces the S-function component in the working folder. After the build, a new model window is displayed.

    Optionally you can save the generated model, for example as SourceSubsys_Sfunction.

  10. You can now copy the S-Function block generated 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 performs 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.

Tunable Parameters in Generated S-Functions

You can use tunable parameters in generated S-functions in two ways:

Block parameters that you declare as 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 system target files. 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 About C MEX S-Functions and Choosing a MATLAB API for Your Application.

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 model configuration parameter Use value for tunable parameters.

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

System Target File

The rtwsfcn.tlc system target file is provided for use with the S-function target.

Checksums and the S-Function Target

The code generator creates a checksum for a model and uses the checksum during the build process for code reuse, model reference, and external mode features.

The code generator calculates a model checksum by

  1. 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.

  2. 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 code generator applies the subsystem and model checksums as follows:

  • Code reuse — If two subsystems in a model have the same checksum, the code generator produces code for one function only.

  • Model reference — If the current model checksum matches the checksum when the model was built, the build process does not rebuild referenced models.

  • External mode — If the current model checksum does not match the checksum of the code that is running on the target hardware, the build process generates an error.

Generated S-Function Compatibility

When you build a MEX S-function from your model, the code generator builds a level 2 noninlined S-function. Cross-release usage limitations on the generated code and binary MEX file (for example, *.mexw64) include:

  • S-function target generated code from previous MATLAB release software is not compatible with newer releases. Do not recompile the generated code from a previous release with newer MATLAB release software. Use the same MATLAB release software to generate code for the S-function target and compile the code into a MEX file.

  • You can use binary S-function MEX files generated from previous MATLAB release software with the same or newer releases with the same compatibility considerations as handwritten S-functions. For more information, see S-Function Compatibility.

  • The code generator can generate code and build an executable from a model that contains generated S-functions. This support requires that the S-functions are built with the same MATLAB release software that builds the model. It is not possible to incorporate a generated S-function MEX file from previous MATLAB release software into a model and build the model with newer releases.

S-Function Target Limitations

Limitation on Configuring Inport and Outport Blocks with Continuous Sample Time

The right-click build method for generating an S-function does not preserve continuous sample time for Inport and Outport blocks. Because the sample time is not preserved, simulation of the generated S-Function block can be affected.

Limitations on Using Tunable Variables in Expressions

Certain limitations apply to the use of tunable variables in expressions. When the code generator encounters an unsupported expression while producing code, a warning appears and the equivalent numeric value is generated in the code. For a list of the limitations, see Tunable Expression Limitations.

Parameter Tuning

The S-Function block does not support tuning of tunable parameters with:

  • Complex values.

  • Values or data types that are transformed to a constant (by setting the model configuration parameter Optimization > Default parameter behavior to Inlined).

  • Data types that are not built-in.

If you select these tunable parameters (through the Generate S-Function for Subsystem dialog box):

  • The software produces warnings during the build process.

  • The generated S-Function block mask does not display these parameters.

Run-Time Parameters and S-Function Compatibility Diagnostics

If you set model configuration parameter S-function upgrades needed to warning or error, the code generator instructs you to upgrade S-functions that you create with the Generate S-function feature. This is because the S-function system target file 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 parameter S-function upgrades needed to none.

Limitations on Using Goto and From Block

When using the S-function system target file, the code generator restricts I/O to correspond to the root model Inport and Outport blocks (or the Inport and Outport blocks of the Subsystem block from which the S-function target was generated). The code generator does not produce code 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 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.

Limitations on Building and Updating S-Functions

The following limitations apply to building and updating S-functions using the S-function system target file:

  • You cannot build models that contain Model blocks using the S-function system target file. This also means that you cannot build a subsystem by using the right-click context menu if the subsystem contains Model blocks. This restriction applies only to S-functions generated using the S-function target, not to ERT S-functions.

  • You can build a model with:

    • A toolchain only if the toolchain supports MEX-file generation.

    • A template makefile only if the template makefile is associated with a toolchain that supports MEX-file generation.

  • If you modify the model that generated an S-Function block, the 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 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.

Unsupported Blocks

The S-function format does not support the following built-in blocks:

  • Interpreted MATLAB Function 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

The S-function format does not support blocks from the embeddedtargetslib block library.

SimState Not Supported for Code Generation

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 ModelOperatingPoint. However, SimState is not supported for code generation, including with the S-function system target file.

Profiling Code Performance with TLC Hook Function Not Supported

Profiling the performance of generated code using the Target Language Compiler (TLC) hook function interface described in Profile Code Execution Speed is not supported for the S-function target.

Note

If you have an Embedded Coder® license, see Code Execution Profiling (Embedded Coder) for an alternative and simpler approach based on software-in-the-loop (SIL) or processor-in-the-loop (PIL) simulations.

Limitations on Nesting S-Functions

The following limitations apply to nesting a generated S-Function block in a model or subsystem from which you generate another S-function:

  • The software does not support nonvirtual bus input and output signals for a nested S-function.

  • Avoid nesting an S-function 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 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, name the subsystem or model to be generated as an S-function target uniquely to avoid duplicating existing MEX filenames on the MATLAB path.

Limitations on User-Defined Data Types

The S-function system target file does not support the HeaderFile property that can be specified on user-defined data types, including those based on Simulink.AliasType, Simulink.Bus, and Simulink.NumericType objects. If a user-defined data type in your model uses the HeaderFile property to specify an associated header file, code generation with the S-function system target file disregards the value and does not generate a corresponding include statement.

Limitation on Right-Click Generation of an S-Function Target

If you generate an S-function target by right-clicking a Function-Call Subsystem block, the original subsystem and the generated S-function might not be consistent. An inconsistency occurs when the States when enabling parameter of the Trigger Port block inside the Function-Call Subsystem block is set to inherit. You must set the States when enabling parameter to reset or held, otherwise Simulink reports an error.

Limitation on S-Functions with Bus I/O Signals

If an S-function generated using the S-function target has bus input or output signals, the generated bus data structures might include padding to align fields of the bus elements with the Simulink representation used during simulation. However, if you insert the S-function in a model and generate code using a model target such as grt.tlc, the bus structure alignment generated for the model build might be incompatible with the padding generated for the S-function and might impact the numerical results of code execution. To make the structure alignment consistent between model simulation and execution of the model code, for each Simulink.Bus object, you can modify the HeaderFile property to remove the unpadded bus structure header file. This will cause the bus typedefs generated for the S-function to be reused in the model code.

Limitation on Subsystems with Function-Call I/O Signals

The S-function target does not support creating an S-Function block from a subsystem that has a function-call trigger input or a function-call output.

Data Store Access

When an S-Function in your model accesses a data store during simulation, Simulink disables data store diagnostics.

  • If you created the S-Function from a model, the diagnostic is disabled for global data stores as well.

  • If you created the S-Function from a subsystem, the diagnostic is disabled for the following data stores:

    • Global data stores

    • Data stores placed outside the subsystem, but accessed by Data Store Read or Data Store Write blocks.

Cannot Specify Inport or Outport Block Parameters Through Subsystem Mask

You cannot specify Inport or Outport block parameters by using subsystem mask variables if you want to generate an S-Function block from the subsystem. The software produces an error when you try to run a simulation that uses the S-Function block, for example:

Invalid setting in 'testSystem/Subsystem/__OutputSSForSFun__/Out2' 
for parameter 'PortDimensions'
...

Related Topics