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?

 Accepted Answer

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 Comment

Amir Tadayon
Amir Tadayon on 30 Jan 2022
Edited: Amir Tadayon on 30 Jan 2022
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 30 Jan 2022

Edited:

on 30 Jan 2022

Community Treasure Hunt

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

Start Hunting!