Retrieve multiple fields with similar names from a struct

15 views (last 30 days)
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?

Accepted Answer

Stephen23
Stephen23 on 7 Oct 2022
Moved: Stephen23 on 7 Oct 2022
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 Comment
Magnus Schneider
Magnus Schneider on 7 Oct 2022
Moved: Stephen23 on 7 Oct 2022
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?

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!