无法使用 parfor 写入矩阵行

Unable to write to matrix lines with parfor

如何使用 parfor 写入结果矩阵行?

代码示例:

xCount = 10;
yCount = 20;
area = xCount*yCount;
PP = nan(area,3);

parfor x = 1:10
    for y = 1:20
        id = y + (x-1)*yCount; % global PP line id.
        z = x^2+y*10; % my stuff to get Z.
        PP(id,:) = [x y z]; % write to PP line
    end
end

The PARFOR loop cannot run due to the way variable 'PP' is used.

其实我说的是"Valid indices are restricted within PARFOR loops"。它说 MATLAB 不连续地迭代 parfor 循环的原因,意味着它可以像 5 2 4 1 3 那样以半随机顺序进行迭代,而不是 1 2 3 4 5。这意味着为了知道 PP MATLAB 必须在何处存储您的结果,它想在进入并行环境之前知道不同迭代不会调用任何行,以避免从工作人员那里取回结果时发生冲突.

解决方案是 PP 以预先知道索引存储位置的方式构建,例如通过在循环之前创建一个二维数组来存储内容:

xCount = 10;
yCount = 20;
area = xCount*yCount;
PP(xCount,yCount) = 0;
y=1:yCount;

parfor x = 1:xCount
    z = x^2+y.*10; % my stuff to get Z.
    PP(x,:) = z; % write to PP line
end
%// Go to the [x y z] format
PP = [repmat((1:yCount).',xCount,1),repmat((1:xCount).',yCount,1), PP(:)];

在这种情况下,我个人不会做最后一行,因为它为每个有用值存储三个双精度值 (z),而在循环出来的二维矩阵中它只存储 1 double 可以通过简单地读取 PP(x,y) 来索引。因此,存储相同数量的有用数据需要 3 倍的内存。