MATLAB: Error storing structure within parfor

for loopparforvariable

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.

Best Answer

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);