How to Run an Indeterminate Number of Simulations with parsim?

6 views (last 30 days)
I want to use parsim in Simulink to run a variable (non-fixed) number of simulations, where the number of iterations may depend on the results of each simulation. Normally, parsim requires you to specify all simulation input objects ahead of time, but I need a way to dynamically trigger additional simulations based on logic within the simulation itself.
Is there a way to achieve this kind of adaptive or recursive simulation workflow using parsim?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 20 Oct 2025 at 0:00
Edited: MathWorks Support Team on 20 Oct 2025 at 15:47
Yes, you can achieve this by using a recursive call to sim inside the postSimFcn callback of your SimulationInput object. This allows you to implement custom logic that decides whether to run another simulation after each one completes. Below is an example that demonstrates this approach. Note that parsim will only return the output object that is returned on the last recursive call. 

Example: Adaptive Simulation Loop with Recursive postSimFcn

%% create simin array
clear
modelName = 'vdp';
simin = Simulink.SimulationInput(modelName);
simin = simin.setPreSimFcn(@(x) preSimStub(x));
simin = simin.setPostSimFcn(@(x,y) postSimRecurse(x,y,1,3));
%% Call parsim and look at output
simin = [simin,simin];
futures = parsim(simin,'RunInBackground','on','ShowSimulationManager','on','UseFastRestart','On');
wait(futures);
out = fetchOutputs(futures);
% out(1).SimulationMetadata.ExecutionInfo.Diary
out(1).IterCount
%% PreSimFcn to print information to diary
function in = preSimStub(in)
%stub
end
%% PostSimFcn to attach diary to output object
function newOut = postSimRecurse(out,simin,iterCount,maxIter)
if ~isempty(out.ErrorMessage) %if error return
newOut = out;
return
end
if iterCount < maxIter
iterCount = iterCount+1;
simin = simin.setPostSimFcn(@(x,y) postSimRecurse(x,y,iterCount,maxIter));
newOut = sim(simin);
else
newOut = out;
newOut.IterCount = iterCount;
end
end

More Answers (0)

Categories

Find more on Run Multiple Simulations in Help Center and File Exchange

Tags

No tags entered yet.

Products


Release

R2025a

Community Treasure Hunt

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

Start Hunting!