MATLAB: Can parfor be used in the case

for loopnestedparallel computingParallel Computing Toolboxparfor

Hi, I'm a new to parallel computing and was wondering if there is any way around to use parfor in my nested for-loop
for l=1:size(xSample,2)
for m=1:size(ySample,2)
for n=1:size(zSample,2)
shiftedDoseDist=imtranslate(doseDist,[xSample(l),ySample(m),zSample(n)]); %%3D image translation
dose=shiftedDoseDist(index);
TCP_n(n)=function(dose) %%function I'm calculating
end
TCP_m(m)=1/sum(zWeighting)*dot(zWeighting,TCP_n);
end
TCP_l(l)=1/sum(yWeighting)*dot(yWeighting,TCP_m);
end
I'm evaluating a function for each x,y,z translation of a 3D matrix and then doing weighted sum for normalisation (expectation value). I tried just replacing for with parfor for the outerloop and it comes up with an error that the way TCP_n,TCP_l…are defined it is not possible.
Any help would be appreciated!

Best Answer

The problem here turns out to be quite simple to work around. You're assigning to elements of TCP_m in the loop over m, but unfortunately the parfor machinery cannot tell that you're completely overwriting TCP_m to make it into a parfor temporary variable.
In other words, parfor cannot tell that you aren't doing something using TCP_m that depends on the order of iterations of the parfor loop. The fix is simply to completely assign to TCP_m at the start of each iteration of the parfor loop:
parfor l=1:size(xSample,2)
TCP_m = zeros(1, size(ySample,2)); % forces TCP_m to be "temporary"
for m=1:size(ySample,2)
TCP_n = zeros(1, size(zSample,2));
for n ...
end
...
TCP_m(m)=1/sum(zWeighting)*dot(zWeighting,TCP_n);
end
TCP_l(l)=1/sum(yWeighting)*dot(yWeighting,TCP_m);
end
( EDIT just realised that the same applies to TCP_n )
Related Question