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?

 Risposta accettata

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 Commento

Amir Tadayon
Amir Tadayon il 30 Gen 2022
Modificato: Amir Tadayon il 30 Gen 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by