Retrieve multiple fields with similar names from a struct

16 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Structures 的更多信息

标签

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by