Retrieve multiple fields with similar names from a struct

16 ビュー (過去 30 日間)
Magnus Schneider
Magnus Schneider 2022 年 10 月 7 日
移動済み: Stephen23 2022 年 10 月 7 日
Hello, I have a very large struct with different types of data (height, period, direction...), for different time instants for example:
data type fields Hs: Struct.Hs01_01 Struct.Hs01_02 Struct.Hs01_03...
data type fields Ts: Struct.Ts01_01 Struct.Ts01_02 Struct.Ts01_03...
My goal is to create new structs with only one data type each but with all time instants.
TLDR: Is it possible to retrieve the struct fields based on a part of their name and to insert them into a new struct?

採用された回答

Stephen23
Stephen23 2022 年 10 月 7 日
移動済み: Stephen23 2022 年 10 月 7 日
Instead of forcing meta-data (i.e. pseudo-indices) into the fieldnames, why are you not simply using a non-scalar structure? Then this task could be achieved using some very basic indexing.
"Is it possible to retrieve the struct fields based on a part of their name and to insert them into a new struct?"
Obtain the FIELDNAMES, identify the parts of the text you want, use something like STRUCT2CELL or a loop to select the fields that you want, then convert them back to structure. Certainly possible if rather fiddly... but better data design (e.g. non-scalar structure with simple fieldnames) would make this task much easier:
S(1).Hs = 1;
S(1).Ts = 11;
S(2).Hs = 2;
S(2).Ts = 22;
S(3).Hs = 3;
S(3).Ts = 33;
T = S([1,3]) % indexing
T = 1×2 struct array with fields:
Hs Ts
You will have much simpler, more efficient code when you do not force meta-data into fieldnames.
  1 件のコメント
Magnus Schneider
Magnus Schneider 2022 年 10 月 7 日
移動済み: Stephen23 2022 年 10 月 7 日
Thank you very much! That is really good advice. I used struct2cell and a loop to separate the data types and my code is much faster now.
Cheers!
Edit: I am not sure how this works, Is it possible to accept your comment as an answer?

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by