MATLAB: Loop through a multi layered structure

loop structure fields

I have a dataset that consist of a structure in a structure, etc…,
example: data (1×1 struct) with 5 fields (body parts), consists of: – head(1×1 struct), torso(1×1 struct),arm(1×1 struct), leg(1×1 struct), feet(1×1 struct). each struct consists again of 4 fields(types of bones) and these fields consist of 12 fields (measurements),these 12 fields are the same for all bones and body parts.
I want to be able to do a calculation on a specific measurement field of each bone of each body part. How do I do this? So I want to make a loop that goes for example to head.1bone.angle and does the calculation (mean) there and then go to head.2bone.angle, etc.. then to torso.1bones.angle etc… Is this possible to do this?

Best Answer

Use fieldnames and dynamic fields. e.g:
for field = fieldnames(data)'
for subfield = fieldnames(data.(field{1}))'
result = mean(data.(field{1}).(subfield{1}).angle)
end
end