Writing S-Functions    

Simple M-File S-Function Example

This block takes an input scalar signal, doubles it, and plots it to a scope.

The M-file code that contains the S-function is modeled on an S-function template called sfuntmpl.m, which is included with Simulink. By using this template, you can create an M-file S-function that is very close in appearance to a C MEX S-function. This is useful because it makes a transition from an M-file to a C MEX-file much easier.

Below is the M-file code for the timestwo.m S-function.

Below are the S-function subroutines that timestwo.m calls.

To test this S-function in Simulink, connect a sine wave generator to the input of an S-Function block. Connect the output of the S-Function block to a Scope. Double-click the S-Function block to open the dialog box.

You can now run this simulation.

Example - Continuous State S-Function

Simulink includes a function called csfunc.m, which is an example of a continuous state system modeled in an S-function. Here is the code for the M-file S-function.

The preceding example conforms to the simulation stages discussed earlier in this chapter. Unlike timestwo.m, this example invokes mdlDerivatives to calculate the derivatives of the continuous state variables when flag = 1. The system state equations are of the form

so that very general sets of continuous differential equations can be modeled using csfunc.m. Note that csfunc.m is similar to the built-in State-Space block. This S-function can be used as a starting point for a block that models a state-space system with time-varying coefficients.

Each time the mdlDerivatives routine is called it must explicitly set the values of all derivatives. The derivative vector does not maintain the values from the last call to this routine. The memory allocated to the derivative vector changes during execution.


  Examples of M-File S-Functions Example - Discrete State S-Function