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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by