Loop through structure elements with parfor

1 回表示 (過去 30 日間)
Matthew Thompson
Matthew Thompson 2019 年 3 月 18 日
コメント済み: Matthew Thompson 2019 年 3 月 20 日
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 件のコメント
Walter Roberson
Walter Roberson 2019 年 3 月 18 日
Perhaps loop over contents of struct2cell ?

サインインしてコメントする。

採用された回答

Edric Ellis
Edric Ellis 2019 年 3 月 19 日
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 件のコメント
Matthew Thompson
Matthew Thompson 2019 年 3 月 20 日
Yes, the struct2cell command was just what I was overlooking. Thank you both.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by