I try to run a model in a loop using parfor
command.
So I wrote the following code:
% control_model.m
warning('off', 'Simulink:Engine:UsingDefaultMaxStepSize');
apool = gcp('nocreate');
if isempty(apool)
apool = parpool('local');
end
load_system('mymodel');
tic
parfor w=1:10
warning('off', 'Simulink:Engine:UsingDefaultMaxStepSize');
w_str=num2str(w);
set_param('mymodel/mysystem','sys', ['tf(',w_str,',[1 ',w_str,'])'] )
sim('mymodel',[],[])
drawnow
end
toc
close_system('mymodel',0);
% delete(poolobj)
Then I will get the following error:
Error using control_model (line 11)
Invalid Simulink object name: mymodel/mysystem
If I run it again, I get the same error (Although using for
instead of parfor
solves this error).
But if I put a load_system('mymodel');
just after parfor
and run it once, the problem is fixed. And even if I remove load_system
command, the error is not shown for the next times anymore.
I am interested in knowing what is happening behind the scene and why the first load_system
does not solve the problem even if I run the program so many times. while the one in parfor
fix the problem even if being removed in the next time calling the script?
I think you need to load the model on the worker (see sim in parfor with Normal Mode in the documentation for more details), so your load_system
needs to be within the parfor
loop:
tic
parfor w=1:10
load_system('mymodel');
warning('off', 'Simulink:Engine:UsingDefaultMaxStepSize');
w_str=num2str(w);
set_param('mymodel/mysystem','sys', ['tf(',w_str,',[1 ',w_str,'])'] )
sim('mymodel',[],[])
drawnow
end
toc