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.
The problem here is that you are assigning to part of total_results
during the loop, but not in a "sliced" manner. It's probably simpler to collect up the names and values separately, and then use cell2struct
after the parfor
loop, like this:
N = 10;
names = cell(1, N);
results = cell(1, N);
parfor i = 1:10
name = sprintf('result_%i',i)
names{i} = name;
results{i} = struct('a', rand(i), 'b', rand(i));
end
total_results = cell2struct(results, names, 2);
EDIT another way of slicing the outputs (as suggested in the comments) is to use
parfor i = 1:10
total_results(i).result = struct('a', rand(i), 'b', rand(i));
end
In this case, this works because the first-level indexing expression is a "sliced" expression.