Slicing variable in parfor loop

8 vues (au cours des 30 derniers jours)
Arnab Samaddar-Chaudhuri
Arnab Samaddar-Chaudhuri le 17 Nov 2022
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.

Réponse acceptée

Edric Ellis
Edric Ellis le 17 Nov 2022
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
Starting parallel pool (parpool) using the 'Processes' profile ... Connected to the parallel pool (number of workers: 2).
celldisp(out1)
out1{1} = 2 3 4 3 4 5 4 5 6 5 6 7
celldisp(out2)
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];
end
  1 commentaire
Arnab Samaddar-Chaudhuri
Arnab Samaddar-Chaudhuri le 18 Nov 2022
Thank you for the elegant solution. Its running perfectly.

Connectez-vous pour commenter.

Plus de réponses (0)

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by