Slicing variable in parfor loop

조회 수: 5(최근 30일)
Arnab Samaddar-Chaudhuri
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;
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.

채택된 답변

Edric Ellis
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];
Starting parallel pool (parpool) using the 'Processes' profile ... Connected to the parallel pool (number of workers: 2).
out1{1} = 2 3 4 3 4 5 4 5 6 5 6 7
out2{1} = 1 2 3 2 4 6 3 6 9 4 8 12
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];
  댓글 수: 1
Arnab Samaddar-Chaudhuri
Arnab Samaddar-Chaudhuri 2022년 11월 18일
Thank you for the elegant solution. Its running perfectly.

댓글을 달려면 로그인하십시오.

추가 답변(0개)


Find more on Startup and Shutdown in Help Center and File Exchange




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by