fitoption 在 parfor 内被清除?

fitoption cleared inside parfor?

我试图通过使用并行性来加速大量数据与 MATLAB 的拟合,但我遇到了一个相当奇怪的问题。

我试图找出问题所在,希望有人能对正在发生的事情有所了解。这是示例代码:

f = @(a, x) a*x;
fitopt = fitoptions(f);

for i = 1:5
  disp(fitopt);
end

如果我运行上面的代码,fitopt的内容会按预期写5次。但是,如果我用 parfor 循环替换 forfitopt 将设置为空并且不会显示任何内容。

知道哪里出了问题吗?

我的配置:windows 7、64 位

上的 MATLAB 2014a

以下基于MATLAB版本R2016b...

据我所知,这似乎是 MATLAB 正确 broadcast (or not) certain class objects to the parfor workers. The fitoptions function returns an object of class curvefit.nlsqoptions in your example. Going through the Curve Fitting Toolbox code, one can see that these objects are still defined using an older UDD class system (a good introduction by Donn Shull can be found on Undocumented MATLAB). Although the newer MCOS(MATLAB Class 对象系统)多年前引入的能力的问题,您仍然可以找到一个数字使用 UDD 定义的对象数。

在你的例子中,fitopt 应该是 broadcast (i.e. copied) to each of the workers, but instead fitopt is set to [] within the parfor loop. If we try this with another class object defined using the newer class system (like those created by fittype),那么广播工作正常。比如这个测试代码:

f = @(a, x) a*x;
uddObj = fitoptions(f);
mcosObj = fittype(f);

parfor i = 1:3
  fprintf('\nWorker %d:\n', i);
  uddObj
  mcosObj
end

产生这个输出:

Worker 2:

uddObj =
     []

mcosObj = 
     General model:
     mcosObj(a,x) = a*x

Worker 1:

uddObj =
     []

mcosObj = 
     General model:
     mcosObj(a,x) = a*x

Worker 3:

uddObj =
     []

mcosObj = 
     General model:
     mcosObj(a,x) = a*x

所以,简而言之,parfor 循环似乎无法正确广播 UDD 样式对象。一种解决方法是在 parfor 循环中创建这些对象,避免广播:

f = @(a, x) a*x;

parfor i = 1:5
  fitopt = fitoptions(f);  % Function handle f broadcasts just fine
  disp(fitopt);
end

您还可以通过创建索引到的对象数组来创建 sliced variable

f = @(a, x) a*x;
fitopt = repmat(fitoptions(f), [1 5]);

parfor i = 1:5
  disp(fitopt(i));
end