Borrar filtros
Borrar filtros

How to compute mean value of a field in a struct?

36 visualizaciones (últimos 30 días)
Gian Marco Ricci
Gian Marco Ricci el 1 de Oct. de 2024 a las 15:23
Comentada: Matt J el 1 de Oct. de 2024 a las 18:07
Hi everyone, writing here since I can’t find the solution to a problem I’m encountering. I need to compute the mean of some fields in a struct I created (see the file attached), but I can’t directly access this fields. It is a 1x31 struct. Each cell of the struct contains 3 fields (Azimuth, Colatitude, W) which are struct arrays. I’d need to compute the mean value of some of these fields cells since I need only 1 value for each cell but some contain more than one. For example, I wanted to compute mean(features{1}.azimuth(7)) but it says that the dot indexing is not supported for the struct. Hope you can help me, I know it is quite a complex structure! You’ll find the .mat attached

Respuesta aceptada

Stephen23
Stephen23 el 1 de Oct. de 2024 a las 15:51
Movida: Cris LaPierre el 1 de Oct. de 2024 a las 17:55
Rather than nesting lots of separate structures in a cell array, why not just use one structure array?:
C = load('featuresnew.mat').merged_features
C = 33x1 cell array
{1x31 struct} {1x31 struct} {1x31 struct} {1x31 struct} {1x31 struct} {1x31 struct} {1x31 struct} {1x31 struct} {1x31 struct} {1x31 struct} {1x31 struct} {1x31 struct} {1x31 struct} {1x31 struct} {1x31 struct} {1x31 struct}
S = vertcat(C{:}) % one structure array
S = 33x31 struct array with fields:
azimuth colatitude W
Simpler data design allow simpler (and therefore generally more reliable and more efficient) code:
M = S;
for k = 1:numel(S)
M(k) = structfun(@mean,S(k),'uni',0);
end
M(1,7)
ans = struct with fields:
azimuth: 80.1430 colatitude: 60.8945 W: 0.0663
  2 comentarios
Gian Marco Ricci
Gian Marco Ricci el 1 de Oct. de 2024 a las 16:57
Movida: Cris LaPierre el 1 de Oct. de 2024 a las 17:55
thank you! very very smart and useful <3
Matt J
Matt J el 1 de Oct. de 2024 a las 18:07
@Gian Marco Ricci If so, you should Accept-click the answer.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Structures en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by