C++ while loop in S-Function Builder

조회 수: 4 (최근 30일)
Faris
Faris 2021년 4월 26일
답변: Amish 2024년 5월 28일
Hello everyone,
I am currently implementing a c++ code within Matlab using the S-Function builder. Now within my c++ Code I have a method in a class that has a while loop in it. It needs to stay like that so changing c++ code is out of the question.
void my_function(){
while(my_condition){
% do some calulations and continuously set condition
}
}
In my S-Function builder, after I read the Inputs and store values in internal variables I want to call this method which will use those variables for calculations. If I do this, simulink freezes on the first sample point because it can't get out of the loop and does not set the outputs at all. Is there a way to get around this ?

답변 (1개)

Amish
Amish 2024년 5월 28일
Hi Faris,
Since Simulink works based on the discrete time steps, the continuous while loop causes the simulation to not being able to advance to the next step. This is what causes the freeze while simulation. To integrate such a function without freezing the simulation, you need to adapt your approach to fit within the Simulink simulation framework.
Since modifying the C++ code directly is not possible, consider wrapping the C++ code call in a MATLAB function that manages the execution flow to prevent the simulation from freezing. This approach might involve checking a condition and breaking the loop based on simulation time or another criterion that changes with each simulation step.
Another option could be to use state machines or timers to control the loop execution within the S-Function. It’s also important to ensure that the loop has proper exit conditions to prevent infinite looping.
You can find the documentation link for the S-functions at: https://www.mathworks.com/help/simulink/sfg/what-is-an-s-function.html#f6-54075
Hope this helps!

카테고리

Help CenterFile Exchange에서 MATLAB Compiler SDK에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by