Finding parfor baffling: Can anybody explain to me why this little bit of code works with for,but not with parfor?

function B = partest
A = 1:4; B = zeros(1,4);
parfor j=1:2
B([j j+2]) = A([j+2 j]);
end
The two bits of the loop access different bits of B, so there should be some way of doing this. My actual application involves large cell arrays, for which something similar holds for the function within the loop.

 Accepted Answer

A = reshape(1:4,2,2);
B = zeros(2);
parfor j=1:2
B(j,:) = A(j,end:-1:1);
end

5 Comments

In your original code, you appear to want B (and maybe also A) to be a sliced variable. But your indexing violates the following requirement from the documentation on sliced variables,
Form of Indexing. Within the list of indices for a sliced variable, one of these indices is of the form i, i+k, i-k, k+i, or k-i, where i is the loop variable and k is a constant or a simple (nonindexed) broadcast variable; and every other index is a scalar constant, a simple broadcast variable, colon, or end.
Sliced variables! That sounds like a good idea. I will read about them. It won't solve my actual problem though, which is a cell array with N elements that are matrices of various sizes, partitioned into two subsets (of different sizes), one of which is modified and the other accessed when j=1 and vice versa when j=2. Am I doomed to be serial?
Cell arrays can be sliced, too. I.e., you could do
parfor i=1:N
ith_Cell=mycell{i};
result{i}=manipulate(ith_Cell);
end
OK. Thanks. I'll have a look at that tomorrow and see what I can do. I expect I'll have more questions. Really struggling to get my head around this. Sorry.
Having given this some thought, I realize that your answer is great, but that I'm asking the wrong question, so I'm going to ask the right question instead.

Sign in to comment.

More Answers (1)

Looks like the interpreter is not smart enough to detect that there is no race condition in the case you present. You could go around that using two loops:
A = 1:4; B = zeros(1,4);
parfor j=1:2
B(j) = A(j+2);
end
parfor j=1:2
B(j+2) = A(j);
end
I assume the operations you actually perform are more complicated than that. Otherwise Matt J's solution is the way to go.

Products

Tags

Community Treasure Hunt

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

Start Hunting!