Writing S-Functions    

Example - Hybrid System S-Function

Simulink includes a function called mixedm.m, which is an example of a hybrid system (a combination of continuous and discrete states) modeled in an S-function. Handling hybrid systems is fairly straightforward; the flag parameter forces the calls to the correct S-function subroutine for the continuous and discrete parts of the system. One subtlety of hybrid S-functions (or any multirate S-function) is that Simulink calls the mdlUpdate, mdlOutputs, and mdlGetTimeOfNextVarHit routines at all sample times. This means that in these routines you must test to determine which sample hit is being processed and only perform updates that correspond to that sample hit.

mixed.m models a continuous Integrator followed by a discrete Unit Delay. In Simulink block diagram form, the model looks like this.

Here is the code for the M-file S-function.


  Example - Discrete State S-Function Example - Variable Sample Time S-Function