Terminate Simulink simulations in parfor loop after some run time

4 views (last 30 days)
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.

Accepted Answer

Harald
Harald on 28 May 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

More Answers (1)

Yifeng Tang
Yifeng Tang on 30 Jul 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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!