Slicing variable in parfor loop
3 views (last 30 days)
Show older comments
Arnab Samaddar-Chaudhuri
on 17 Nov 2022
Commented: Arnab Samaddar-Chaudhuri
on 18 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.
0 Comments
Accepted Answer
Edric Ellis
on 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
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
More Answers (0)
See Also
Categories
Find more on Parallel for-Loops (parfor) 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!