I'm wondering hwo to go around the issue below (this is a simplified version of my code)
method = struct('Len', 1);
parfor nf = 1:3
method.Len = nf^2;
res(nf) = mean(nf+randn(method.Len, 1));
end
The issue is that the struct field cannot be updated within parfor. Is there any workaround to update struct field in a parfor?

 채택된 답변

Voss
Voss 2022년 1월 30일

0 개 추천

I don't know whether it's feasible in your actual code, but you might try making method an array of structs and accessing one element of method within the parfor loop:
try
method = struct('Len', 1)
parfor nf = 1:3
method.Len = nf^2;
res(nf) = mean(nf+randn(method.Len, 1));
end
catch ME
disp(ME.message);
end
method = struct with fields:
Len: 1
Error: Unable to classify the variable 'method' in the body of the parfor-loop. For more information, see Parallel for Loops in MATLAB, "Solve Variable Classification Issues in parfor-Loops".
method = struct('Len', num2cell(ones(1,3)))
method = 1×3 struct array with fields:
Len
parfor nf = 1:3
method(nf).Len = nf^2;
res(nf) = mean(nf+randn(method(nf).Len, 1));
end
disp(res);
0.6226 2.1194 2.9470

댓글 수: 1

Amir Tadayon
Amir Tadayon 2022년 1월 30일
편집: Amir Tadayon 2022년 1월 30일
Thanks Benjamin. This workaround works for me. The way I use your idea was to make an array of struct and update the desired field before parfor.

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

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기

태그

질문:

2022년 1월 30일

편집:

2022년 1월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by