Terminate Simulink simulations in parfor loop after some run time

조회 수: 5 (최근 30일)
Bart Peremans
Bart Peremans 2025년 5월 28일
댓글: Paul 2025년 7월 31일
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