How do I extract data from a structure using a for loop?

4 views (last 30 days)
I have a data structure containing 10 fields. Within each of these fields, there is another field of data that I would like to extract. Using a for loop, how do I extract the final field from each of the 10 fields in the structure? Hope that makes sense :)
  1 Comment
Stephen23
Stephen23 on 28 Nov 2024
Edited: Stephen23 on 28 Nov 2024
"how do I extract the final field from each of the 10 fields in the structure?"
Although they can be sorted in whatever order you want, the order of fields is not something that you usually want to rely upon.
It sounds like you should really flatten your data e.g. by using one non-scalar structure. Then you could probably significantly simplify accessing your data:

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 28 Nov 2024
Not really. Fields are not ordered by number. They have names. What is the name of the "final" field in the 10 upper level fields? Is it the same name in all 10 upper level fields? What are the names of the 10 upper level fields? In general it might be something like this
thisVec = str.field1.deepField;
vec(1) = thisVec(end);
thisVec = str.field2.deepField;
vec(2) = thisVec(end);
and so on for fields 3 through 10. For only 10 I'd recommend you just put in these 20 lines rather than use a for loop where you need to use dynamic field names to access the fields.
If you have any more questions, then attach your data in a .mat file, and code to read it in, with the paperclip icon after you read this:

Walter Roberson
Walter Roberson on 28 Nov 2024
fieldnames = fieldnames(YourDataStructure);
num_fields = length(fieldnames);
last_field_values = cell(num_fields,1);
for FI = 1 : num_fields
current_field = fieldnames{FI};
subfieldnames = fieldnames(YourDataStructure.(current_field));
lastfield_name = subfieldnames{end};
last_field_values{FI} = YourDataStructure.(current_field).(lastfield_name);
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2024b

Community Treasure Hunt

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

Start Hunting!