Error storing structure within parfor

1 Ansicht (letzte 30 Tage)
Mohd Shihabuddin Khan
Mohd Shihabuddin Khan am 8 Okt. 2019
I have a function which runs a parfor loop. Within the loop, I call another function which generates a structure as a result. I need to store all the structures.
function myFunction(arguments)
% do some preliminary calcultions
parfor i = 1:num_sim % number of simulations
name = sprintf('result_%i',i)
% do some calculations and generate a structure as a result called "struct_result"
total_results.(name) = struct_result
end
end
This gives me an error message:
The variable total_results in a parfor cannot be classified.
How can I store the structure "struct_result" from all the simulations? It is a nested structure.

Akzeptierte Antwort

meghannmarie
meghannmarie am 9 Okt. 2019
You could try storing it in a cell array and converting to structure after the parfor:
names = cell(num_sim,1);
results = cell(num_sim,1);
parfor i = 1:num_sim % number of simulations
names{i} = sprintf('result_%i',i);
results{i}= struct_result;
end
total_results = cell2struct(results, names, 1);
  2 Kommentare
Walter Roberson
Walter Roberson am 9 Okt. 2019
This is probably a good idea. You could also generate the field names after the parfor as they depend only on the indices.
parfor needs to be able to establish through static analysis where the output is to be written to, in order to be sure that different workers do not write to the same location. The inference is not advanced enough to extend to fieldnames calculated with sprintf.
Mohd Shihabuddin Khan
Mohd Shihabuddin Khan am 9 Okt. 2019
I tried
total_results(i).result = struct_result
and this worked.
This seems a simpler solution as I don't have to convert back to a struct.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by