Why does my 'S-Function' block Run Four Times per Timestep?

7 views (last 30 days)
My 'S-Function' block has no inputs, only outputs. One output is a counter, representing the number of times my 'S-Function' block is called. The block seems to be called 4 times per timestep when I step through my model.
My model uses a fixed-step ODE4 solver. I thought it was an algebraic loop causing this error, but adding a Unit Delay did not solve my problem.  
Is this behavior expected? How can I make the 'S-Function' block run once per timestep?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 2 Feb 2023
The reason the 'S-Function' block is called four times per step is because the ODE4 solver calls the outputs four times to compute the integral per step (per the fourth-order Runge-Kutta method). These four sub-steps are known as minor steps. This solver has been described in the following documentation:
If you only wants to count the major steps (the steps you see when stepping through in Simulink) then you can modify your S-Function builder in the following way:
1. In the S-Function Builder interface, make sure the "Enable access to SimStruct" is checked in the Settings panel on the right.
2. Change your function slightly to update the counter on major steps only:
void countmein_Outputs_wrapper(uint8_T *y0,
                               real_T *y1,
                               SimStruct *S)
/* Output_BEGIN */
if (ssIsMajorTimeStep(S)) {
    sprintf(y0, "Count is %d", mycounter);
    *y1 = mycounter;
/* Output_END */
The key here is to use the function "ssIsMajorTimestep" function. Please refer to the following documentation for more information on this function:
  1 Comment
tianyuan wang
tianyuan wang on 9 Mar 2023 at 3:45
Edited: tianyuan wang on 9 Mar 2023 at 3:52
I encountered a similar problem.
If I choose the ode4 solver, does the model loop four times in one time step?
Another question is, if I use S-function in my model and call S-function once in a time step, how does ode4 extrapolate the results of S-functions? Does the result of the S-function have to be a function of time t? Or Simulink automatically extrapolate based on the value of S-function?

Sign in to comment.

More Answers (0)




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!