Why is my variable undefined when using parsim?

36 views (last 30 days)
I have a simulink model that runs when I'm not running it in parallel, but it will not run in parallel. In the function that invokes my model I create a class handle object and store it in the base workspace. From within the model I have a Matlab function that calls a function of the object by evaluating it in the base workspace. In parallel mode I get an error saying that this object handle is undefined. But it works fine if I don't run it in parallel mode. 
I've created a simple model that illustrates the problem (you will need to include the files TestClass.m and TestObjSim.slx in the same directory):
objH = TestClass(1);
assignin('base','objH',objH);
% This works:
simOut = sim('TestObjSim');
% Running in parallel doesn't work:
in = Simulink.SimulationInput('TestObjSim');
simout = parsim(in,'TransferBaseWorkspaceVariables','on');
disp(simout.ErrorMessage);

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 14 Apr 2023
Edited: MathWorks Support Team on 14 Apr 2023
The reason the you see the error is because the base workspace is not shared among the workers, To make sure that each worker has access to everything, I would recommend create an initialization function that can be called by each worker to load the data including the class into the worker's base workspace. 
For example,
1) Define a function in loadObject.m.
function loadObject()
objH = TestClass(1);
assignin('base','objH',objH);
2) Load the function in all workers and run parsim:
% Load object in all workers
parfevalOnAll(@loadObject,0);
% Run parallel simulation
in = Simulink.SimulationInput('TestObjSim');
simout = parsim(in,'TransferBaseWorkspaceVariables','on');
For more information about the function parfevalOnAll, please refer to this page:
Although this documentation is talking about parfor, it has some useful discussions about workspace access issue that applies to your case:

More Answers (0)

Categories

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

Tags

No tags entered yet.

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!