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

조회 수: 14 (최근 30일)
Andrea
Andrea 2024년 11월 28일
답변: Walter Roberson 2024년 11월 28일
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
Stephen23
Stephen23 2024년 11월 28일
편집: Stephen23 2024년 11월 28일
"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:

댓글을 달려면 로그인하십시오.

답변 (2개)

Image Analyst
Image Analyst 2024년 11월 28일
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 2024년 11월 28일
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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by