
Terminate Simulink simulations in parfor loop after some run time
7 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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.
0 Commenti
Risposta accettata
Harald
il 28 Mag 2025
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

0 Commenti
Più risposte (1)
Yifeng Tang
il 30 Lug 2025
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
See this Documentation page: https://www.mathworks.com/help/simulink/slref/sim.html#mw_08a7f3fe-c802-4a32-908b-802508fde106
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!