extract/access same fields from multiple structures (it is a nested structure)
47 views (last 30 days)
Show older comments
Narges Raee
on 8 Dec 2021
Commented: Carson Purnell
on 15 Jun 2022
I have 9 structures (1*1 structures), each structure contains 45 fields. some of the field are single values such as : TKE 0.12 in the first structure, TKE 0.005 in the second structure and so on. I am trying to get the TKE fields form these structures and have them in one array (I wanna plot them later). I am not sure how to do it! could anyone please give me a quidance? (by the code: name_of_structure_one.TKE I can get the first TKE which is 0.12 but I want to have all the nine TKE in one array! (TKE is the name of one of the fields)
P.S I put all the 9 structure in one structure using load file_name.mat, thought I can work with it easier maybe! so now I have one structure which has 9 structures in it each structure has 45 fileds in it. how can I get one of the fileds from all 9 structures?
thanks a lot!
0 Comments
Accepted Answer
Walter Roberson
on 8 Dec 2021
temp = [S1; S2; S3; S4; S5; S6; S7; S8; S9];
all_TKE = [temp.TKE];
The above would only work if the structures all have the same fields in the same order. Otherwise,
all_TKE = cellfun(@(S) S.TKE, {S1; S2; S3; S4; S5; S6; S7; S8; S9});
3 Comments
Carson Purnell
on 15 Jun 2022
For anyone else that searches this question: who() is not a solution. It just makes a cell array of your workspace variable names.
A real solution is to not make 9 different structs, but a single scalar struct of length 9, so you can easily access all the fields of name Z with something like [experiments(:).Z].
Alternatively, depending on the complexity of the data, you could use a cell array and hope that nobody else ever wants to know where things are indexed but again it becomes trivial to access data.
Finally, you might be able to use a table in leiu of a cell array to keep things labeled to a degree.
More Answers (0)
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!