C++ while loop in S-Function Builder

8 次查看(过去 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