Writing S-Functions    

Examples of M-File S-Functions

The simple example discussed above (timestwo) has no states. Most S-Function blocks require the handling of states, whether continuous or discrete. The sections that follow discuss four common types of systems you can model in Simulink using S-functions:

All examples are based on the M-file S-function template found in sfuntmpl.m.

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 above 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 value 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.


 A Simple M-File S-Function Example Example - Discrete State S-Function