MATLAB: How to determine which state in the S-Function generated a zero crossing

%scrossingdetectfunctions-functionsimulinkzero

I wish to know how I can tell which specific state in my S-Function has generated a zero crossing, and depending on which state, perform a specific action for that particular state.

Best Answer

S-functions do not by default indicate which state generated a zero crossing. However, it is possible to use SimStruct macros and functions to implement this.
See the attached files "TS_sfun_zc_sat.c" (remember to MEX this file before running the model) and "sf_zc_example.mdl" for one possible implementation. This is a modification of the built-in demo "sfcndemo_sfun_zc_sat.mdl". The code in the S-function has been modified such that it outputs not only the saturated signal but also the current mode (state) and a flag to indicate if that time step was a 'crossing-over' between modes. This is achieved by modifying 'mdlOutputs' slightly and making use of a Work vector to store the value of the previous mode.
An alternate method is as follows:
- Use the Adaptive ZC algorithm and specify an appropriate value of the ZC threshold.
- In the mdlOutput method of your S-Function, implement a 'for' loop with an 'if' statement to verify if any of the zero crossing signals (ssGetNonsampledZCs) are smaller than the ZC threshold.
- If you want more accuracy, you can use a Dwork vector to store the previous value of ssGetNonsampledZCs and detect if it really crossed zero.