MATLAB: Alternative to using structs as reduction variables in parfor loop

cell arraysMATLABparforstruct

My code initializes a struct (say init_s) with about 9 fields before going into a parfor loop of iterations (as s). Over a single iteration, the empty arrays in s are filled with data. I'd like to add these arrays together, without having to create 9 different variables for each field. How could I go about doing that? Here is a minimum working example:
init_s = struct('f1',ones(10,1),'f2',zeros(10,1),'f3',50*ones(15,1))
parfor iter = 1:10
s = init_s;
s.f1 = s.f1 * 2;
s.f2 = s.f2 + 5;
s.f3 = s.f3 - 1;
end
I'd like to add the generated arrays individually (s.f1 over all iter, s.f2 over all iter, etc.) so that I can average them later. How can I do that without having to create a lot of variables? Or if I have to, how do I access them in a loop using fieldnames?

Best Answer

s(1:2) = struct('f1',ones(10,1),'f2',zeros(10,1),'f3',50*ones(15,1))
s = 1x2 struct array with fields:
f1 f2 f3
sc = struct2cell(s(:))
sc = 3x2 cell array
{10×1 double} {10×1 double} {10×1 double} {10×1 double} {15×1 double} {15×1 double}
totals = arrayfun(@(R) sum(cat(3,sc{R,:}),3), (1:size(sc,1)).', 'uniform', 0)
totals = 3x1 cell array
{10×1 double} {10×1 double} {15×1 double}
struct_total = cell2struct(totals, fieldnames(s), 1)
struct_total = struct with fields:
f1: [10×1 double] f2: [10×1 double] f3: [15×1 double]