Slicing variable in parfor loop
조회 수: 6 (최근 30일)
이전 댓글 표시
Arnab Samaddar-Chaudhuri
2022년 11월 17일
댓글: Arnab Samaddar-Chaudhuri
2022년 11월 18일
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개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!