Slicing variable in parfor loop
4 次查看(过去 30 天)
显示 更早的评论
I have a problem with parfor. If I run the code, ofcourse I get an error " The PARFOR loop cannot run due to the way the variable 'completeCellPositions' and 'cellPos' is used ", since there is dependency of the value count from previous loop run.
My code so far:
count = 1;
xRange = [-2000,2000];
yRange = [-500,500];
parfor cellCOMX = xRange(1,1):5:xRange(1,2)
for cellCOMY = yRange(1,1):5:yRange(1,2)
[completeCellPositions{1,count}, cellPos{1,count}] = doesSomething(cellCOMX, cellCOMY);
count = count+1;
end
end
I am not sure, how to place sliced variable in this scenario. I cannot simply write
[completeCellPositions{1,cellCOMX}, cellPos{1,cellCOMX}] = doesSomething(cellCOMX, cellCOMY);
Any suggestion, how to solve this issue?
PS: Ideally, I would like to use parfor for both for loops, but I can settle for even one parfor.
0 个评论
采纳的回答
Edric Ellis
2022-11-17
In this case, you don't actually have a data dependency between the loop iterations. You can use a parfor reduction to do this, like so:
out1 = {};
out2 = {};
parfor i = 1:4
for j = 1:3
% Some calculation
[tmp1, tmp2] = deal(i + j, i * j);
% Build up out1 and out2 using concatenation
out1 = [out1, tmp1];
out2 = [out2, tmp2];
end
end
celldisp(out1)
celldisp(out2)
There are additional restrictions you need to overcome - firstly, the range of your parfor loop must be consecutive integers. You could also combine the loops using ind2sub. Something a bit like this:
xVec = -2000:5:2000;
yVec = -500:5:500;
nX = numel(xVec);
nY = numel(yVec);
out1 = {};
out2 = {};
parfor idx = 1:(nX*nY)
[i, j] = ind2sub([nX, nY], idx);
xVal = xVec(i);
yVal = yVec(j);
% Some calculation
[tmp1, tmp2] = deal(xVal + yVal, xVal * yVal);
% Build up out1 and out2 using concatenation
out1 = [out1, tmp1];
out2 = [out2, tmp2];
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!