For loop in parfor loop

조회 수: 6 (최근 30일)
Niels
Niels 2015년 3월 10일
댓글: Niels 2015년 3월 10일
Dear all, I am trying to run the following script
a = linspace(0,10);
parfor ii=1:2
for jj=1:length(a)
x(ii,jj) = rand;
end
end
which fails with an "Error: The variable x in a parfor cannot be classified." Is this a bug in Matlab? I would simply consider the vector "a" a broadcast variable, since "a" and "length(a)" are unmodified by the script.
How would you recommend to fix the script, taking into account that length(a) should be evaluated inside the parfor loop?
Thanks, Niels

채택된 답변

Greig
Greig 2015년 3월 10일
I don't know the details (perhaps another answer can get technical), but parfor loops don't like assigning values to things like x(ii, jj) directly, so you have to use temporary variables that are accessed only in the parfor loop. Try something like this....
a = linspace(0,10);
x=NaN(2,length(a)); % pre-allocated for speed
parfor ii=1:2
tmp_var=NaN(1,length(a)); % pre-allocate a temporary variable
for jj=1:length(a)
tmp_var(jj) = rand;
end
x(ii,:) = tmp_var; % assign it to x
end

추가 답변 (1개)

Edric Ellis
Edric Ellis 2015년 3월 10일
편집: Edric Ellis 2015년 3월 10일
The limitation you're hitting here is that any for loop nested inside a parfor loop must have constant bounds to allow slicing. In your case, the bounds are constant, so you can simply write:
a = linspace(0,10);
n = length(a); % extract length outside PARFOR
parfor ii=1:2
for jj=1:n % constant bounds loop inside PARFOR
x(ii,jj) = rand;
end
end
This limitation is documented here.
In the case where your inner for loop has non-constant bounds, then @Greig's solution is the way to go.
  댓글 수: 1
Niels
Niels 2015년 3월 10일
Great, thank you both for your replies, I will follow your suggestions! :-) Best regards, Niels

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

카테고리

Help CenterFile Exchange에서 Parallel Computing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by