Borrar filtros
Borrar filtros

loop through a multi layered structure

15 visualizaciones (últimos 30 días)
N
N el 13 de Ag. de 2014
Editada: Stephen23 el 16 de En. de 2018
I have a dataset that consist of a structure in a structure, etc...,
example: data (1x1 struct) with 5 fields (body parts), consists of: - head(1x1 struct), torso(1x1 struct),arm(1x1 struct), leg(1x1 struct), feet(1x1 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?

Respuesta aceptada

Guillaume
Guillaume el 13 de Ag. de 2014
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
  5 comentarios
Tiasa Ghosh
Tiasa Ghosh el 16 de En. de 2018
If suppose I wanted to combine each element at each sub-level of the nested structure into one string, how do I run the loop to output such a string? Any hint or help is welcome. Thanks!
Stephen23
Stephen23 el 16 de En. de 2018
Editada: Stephen23 el 16 de En. de 2018
"If suppose I wanted to combine each element at each sub-level of the nested structure into one string, how do I run the loop to output such a string?"
Simply split the string at the delimiter and then call getfield / setfield directly.

Iniciar sesión para comentar.

Más respuestas (2)

Azzi Abdelmalek
Azzi Abdelmalek el 13 de Ag. de 2014
Use structfun function

Guillaume
Guillaume el 13 de Ag. de 2014
Or using structfun, if you want the result as a structure:
structfun(@(part) structfun(@(bone) mean(bone.angle), part, 'UniformOuput', false), data, 'UniformOutput', false)
You can do away with the first UniformOutput but not the second.

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by