Copy fields from object cell array into struct array

Hi everyone,
I have a cell array of cfit objects, let's call it objArray. I want to copy several fields (or I guess I should call them attributes) from this objArray to build a struct array. I know I can do it the following way :
mystruct = cellfun(@(x) struct('field1',x.field1,'field2',x.field2), objArray,'UniformOutput',true);
However I would like a way of doing this with a function that takes as input objArray as well as a cell array containing the names of the fields I am willing to copy. It would look like this :
mystruct = obj2struct(objArray,fieldNames);
Any help is welcome :) thanks

 採用された回答

Matt J
Matt J 2020 年 10 月 13 日
編集済み: Matt J 2020 年 10 月 13 日

2 投票

I would just keep it simple and use a for-loop. There will be no performance gains from doing it some other way. Any abbreviation of this using cellfun or arrayfun will be syntactic sugar at best.
function mystruct = obj2struct(objArray,fieldNames)
M=numel(objArray);
N=numel(fieldNames);
for m=M:-1:1
for n=1:N
field=fieldNames{n};
mystruct(m).(field)=objArray{m}.(field);
end
end
end

3 件のコメント

Hugo Fluhr
Hugo Fluhr 2020 年 10 月 14 日
thanks for your help, indeed this seems to be the best solution
Hugo Fluhr
Hugo Fluhr 2020 年 10 月 14 日
I just noticed that your outer for loop loops from the end of the obj array to the start, any particular reason for this?
Matt J
Matt J 2020 年 10 月 14 日
It avoids mystruct growing in length throughout the loop, which is inefficient. With a descending loop, the whole mystruct array will be allocated once the first outer iteration completes.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

製品

リリース

R2017b

質問済み:

2020 年 10 月 13 日

コメント済み:

2020 年 10 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by