Parfor loops skipping an index

조회 수: 2 (최근 30일)
Oyeniyi
Oyeniyi 2015년 1월 1일
댓글: Edric Ellis 2015년 1월 6일
When I run the piece of code below, the result shows that there is an index that is not executed...
temp=struct('myfield1',num2cell(ones(2,6)));
parfor i = 1:6
temp(2,i).myfield1 = i*4;
temp(2,i).myfield2 = i;
end
I have run this on a few computers and one of the index is always not executed (or at least seems to). For example, I could have temp(2,6).myfield1=1 and temp(2,6).myfield2=[] instead of temp(2,6).myfield1=24 and temp(2,6).myfield2=6.
Could it be because I did not define all the fields beforehand?

답변 (1개)

Edric Ellis
Edric Ellis 2015년 1월 6일
Yes, defining all the fields of temp beforehand works around this problem, like so:
temp=struct('myfield1',num2cell(ones(2,6)), 'myfield2', []);
parfor i = 1:6
temp(2,i).myfield1 = i*4;
temp(2,i).myfield2 = i;
end
% Assertions:
assert(isequal(4:4:24, [temp(2, :).myfield1]));
assert(isequal(1:6, [temp(2, :).myfield2]));
  댓글 수: 2
Oyeniyi
Oyeniyi 2015년 1월 6일
I also noticed earlier that pre-defining the fields eliminates the problem but it is not really feasible to do this for my application.
Do you know why an index is skipped in the initial instance? Many thanks.
Edric Ellis
Edric Ellis 2015년 1월 6일
I'm afraid I know of no other workaround involving structures. Could you perhaps return cell arrays of data with which you can recreate the structure outside the PARFOR loop?

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by