Variable in a parfor cannot be classified

조회 수: 1 (최근 30일)
Gerard Capes
Gerard Capes 2019년 4월 30일
댓글: Gerard Capes 2019년 5월 1일
I'm attempting to convert some code to use a parfor, and have run into difficulty. A simplified example is given below, which doesn't work. I have read the documentation and lots of answers, but nonetheless can't seem to work it out.
% Preallocate array
var1 = zeros(5);
parfor i = 1:5
for j = 2:6
var1(j, :) = j;
end
end
Preallocating the arrays within the parfor gives no errors, but I don't understand why this works but the initial example doesn't. Could someone please put me out of my misery and explain this, or point me to the right bit of documentation? Thanks
parfor i = 1:5
% Preallocate array
var1 = zeros(5);
for j = 2:6
var1(j, :) = j;
end
end

채택된 답변

Walter Roberson
Walter Roberson 2019년 4월 30일
In the second version, you are creating a local variable for use within the worker, whose value within the worker will be discarded and not returned to the client.
In the first version, you are creating a variable in the client and updating it in the worker, but every worker would be competing to update the same locations. In your particular case you can establish that the result would be the same as long as you used at least one worker, but consider the very slight modification:
var1 = zeros(5);
parfor i = 1:5
t = i;
for j = 2:6
var1(j, :) = j + t;
end
end
Now what would you expect the result to be? If you were using for instead of parfor you would recognize that you were overwriting all of rows 2 to 6 each time, and so the result would be the same as if you had executed only the last loop,
for i = 5
t = i;
for j = 2:6
var1(j,:) = j + t;
end
end
but with parfor the iterations can be done in any order and the workers would be competing to write to the same array. Iteration 2 might happen to be the last one to write to var1(5,3) but iteration 4 might happen to be the last one to write to var1(5,2) .
MATLAB does not permit this. You can only write to an output variable using the loop control variable. For example,
var1 = zeros(6,5);
parfor i = 1:5
t = i;
v1 = zeros(6,1);
for j = 2:6
v1(j,:) = j + t;
end
var1(:, i) = v1;
end
  댓글 수: 1
Gerard Capes
Gerard Capes 2019년 5월 1일
D'oh!
It seems so obvious now that I understand it. Thanks for the clear explanation which enabled me to join the dots :)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by