Retrieve multiple fields with similar names from a struct

8 Ansichten (letzte 30 Tage)
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?

Akzeptierte Antwort

Stephen23
Stephen23 am 7 Okt. 2022
Verschoben: Stephen23 am 7 Okt. 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 Kommentar
Magnus Schneider
Magnus Schneider am 7 Okt. 2022
Verschoben: Stephen23 am 7 Okt. 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?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Produkte


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by