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 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