Is there a way to extract specific fields from a structure?

43 ビュー (過去 30 日間)
TastyPastry
TastyPastry 2016 年 6 月 23 日
回答済み: Itsik Adiv 2018 年 9 月 3 日
I have a 1x1 structure with a large number of fields of which I'd like to extract some subset. I don't want to have to use
[myst.field1 myst.field2 myst.field3]...
Is there a way to shorten the code so I only have to type myst once and just extract the fields necessary? The structure name is nested within another structure so the code can get lengthy.

採用された回答

Stephen23
Stephen23 2016 年 6 月 23 日
編集済み: Stephen23 2016 年 6 月 23 日
Solution
>> S.a = 'Hello';
>> S.b = 'World';
>> C = {'a','b'};
>> D = cellfun(@(f)getfield(S,f),C,'UniformOutput',false);
>> horzcat(D{:})
ans = HelloWorld
Take a look at fieldnames.
Improvement
Note that if the fieldnames really are numbered like that then a much better solution would be to consider using a non-scalar array. A non-scalar structure is a much better way to store data, compared to numbered fieldnames. Using a non-scalar structure would avoid having to perform slow and complicated tricks like this, instead you could use the neat and fast methods shown in the link:
>> S(1).f = 'Hello';
>> S(2).f = 'World';
>> [S.f]
ans = HelloWorld
See how choosing the best data storage makes a huge difference to the quality of code!
  2 件のコメント
TastyPastry
TastyPastry 2016 年 6 月 23 日
Oh yeah they're not numbered fieldnames. The issue I'm facing is that the fieldname data is user inputted and comes in random order so I'm trying to avoid indices.
Stephen23
Stephen23 2016 年 6 月 23 日
@TastyPastry: fair enough. Then my solution does exactly what your question asks for: it concatenates the fields together.

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

その他の回答 (2 件)

Thorsten
Thorsten 2016 年 6 月 23 日
編集済み: Thorsten 2016 年 6 月 23 日
help getfield
  1 件のコメント
TastyPastry
TastyPastry 2016 年 6 月 23 日
編集済み: TastyPastry 2016 年 6 月 23 日
See I did look at getfield(), but it seems like getfield() only works on single fields. I can see that it's able to get the same field for multiple structures in an array and retrieve multiple pieces of data for that field using indexing, but I can't see how it works for multiple fields.
Okay so I tried
getfield(myst,'field1','field2','field3'...);
but that gives me an error Attempt to reference field of non-structure array.

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


Itsik Adiv
Itsik Adiv 2018 年 9 月 3 日
You can use rmfield instead:
fieldsList = fieldnames(myst); myst = rmfields(myst, fieldnames{4:end});
Of course you can replace indices 4:end with any valid indexing logic you wish

カテゴリ

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