How to Run an Indeterminate Number of Simulations with parsim?
6 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2025-10-20,0:00
编辑: MathWorks Support Team
2025-10-20,15:47
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?
采纳的回答
MathWorks Support Team
2025-10-20,0:00
编辑:MathWorks Support Team
2025-10-20,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.
%% 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
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Run Multiple Simulations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!