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

2 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)) {
    mycounter++;
    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:

More Answers (0)

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!