Terminate Simulink simulations in parfor loop after some run time

19 次查看(过去 30 天)
I am running multiple Simulink/Simscape models in parallel using a parfor loop and would like to stop simulations prematurely if they exceed a predefined time for running. Some of the simulations tend to get trapped with very small time steps, making them run for ages. These simulations need to be stopped.
I was inspired by the following piece of code:
model = 'mymodel';
load_system(model)
timeout = 10;
set_param(model,'SimulationCommand','start')
tic;
while(true)
if not(strcmpi(get_param(model,'SimulationStatus'),'running'))
disp('simulation exited')
break;
end
if toc>=timeout
disp('timout reached')
set_param(model,'SimulationCommand','stop')
break;
end
pause(1);
end
bdclose(model)
The code works nicely. However, when embedding this code in a parfor loop, I get the following error:
'You cannot use set_param to run a simulation in a MATLAB session that does not have a display.'
Is there a way to resolve this problem?
The regular 'sim' functionality does not allow to stop the simulation prematurely based on some run time. I looked for an alternative implementation in Simulink itself with a clock and 'Stop Simulation' object, but unfortunately there is no clock available which represents real-world time which can trigger the stop.

采纳的回答

Harald
Harald 2025-5-28
Hi,
a workaround would be to use the tic/toc functions inside a MATLAB Function block. Attachments currently don't seem to work on the platform, so I have added a screenshot. The code of the MATLAB Function block:
function y = fcn()
coder.extrinsic("tic", "toc")
persistent tstart
if isempty(tstart)
tstart = tic;
end
y = 0;
y = toc(tstart);
Best wishes,
Harald

更多回答(1 个)

Yifeng Tang
Yifeng Tang 2025-7-30
Consider use the sim command to execute your model, and set a maximum simulation run time using the "TimeOut" option.
For example:
simin = Simulink.SimulationInput("MyModel"); % simulation input for MyModel
simin = setModelParameter(simin,TimeOut=60); % set up max wall clock
simout = sim(simin); % run simulation

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by