Why is my variable undefined when using parsim?
18 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2018-8-30
编辑: MathWorks Support Team
2025-11-10
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);
采纳的回答
MathWorks Support Team
2025-11-10
编辑:MathWorks Support Team
2025-11-10
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:
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Simulink Functions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!