Loop through structure elements with parfor

1 view (last 30 days)
I have a structure with programatically generated fieldnames (let's call it myStruct), and an optimization program (let's call it optfunc) needs to run on data contained in each fieldname. I would like to use parfor to accelerate the process, but the normal way to loop through structs creates unclassified variables. Any tips on how this can be fixed? E.g.:
myFields = fieldnames(myStruct);
nFields = size(myFields,1);
parfor iField = 1:nFields
dataSet = myStruct.(myFields{iField});
optOut = optfunc( dataSet );
end

Accepted Answer

Edric Ellis
Edric Ellis on 19 Mar 2019
Given the following example data
myStruct = struct('one', rand(1), ...
'two', rand(2), ...
'three', rand(3));
My slight adaption of your program works correctly:
myFields = fieldnames(myStruct);
nFields = size(myFields,1);
out = NaN(1, nFields);
parfor iField = 1:nFields
dataSet = myStruct.(myFields{iField});
out(iField) = max(dataSet(:));
end
But note that myStruct is not sliced in this case - as @Walter suggests, you could use struct2cell to achieve that.
myContents = struct2cell(myStruct);
out2 = NaN(1, numel(myContents));
parfor iField = 1:numel(myContents)
dataSet = myContents{iField};
out2(iField) = max(dataSet(:));
end
  1 Comment
Matthew Thompson
Matthew Thompson on 20 Mar 2019
Yes, the struct2cell command was just what I was overlooking. Thank you both.

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!