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