Loop through structure elements with parfor

1 vue (au cours des 30 derniers jours)
Matthew Thompson
Matthew Thompson le 18 Mar 2019
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
  1 commentaire
Walter Roberson
Walter Roberson le 18 Mar 2019
Perhaps loop over contents of struct2cell ?

Connectez-vous pour commenter.

Réponse acceptée

Edric Ellis
Edric Ellis le 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 commentaire
Matthew Thompson
Matthew Thompson le 20 Mar 2019
Yes, the struct2cell command was just what I was overlooking. Thank you both.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by