average of field in a structure with an if condition

2 visualizaciones (últimos 30 días)
etudiant_is
etudiant_is el 2 de Mzo. de 2016
Comentada: etudiant_is el 2 de Mzo. de 2016
So I have a structure S with two fields field1 and field2 What i want to do is If field1 is equal to a value x , I sum (then get the average of) the values in field2 I can do it with a for loop and if inside of it but is there a more faster way to do it.
Example
S.a field1 field2
2 4
0 6
1 5
2 3
If x=2, the result i want to get is 3.5 (the average of values in field2) where field1 =2
P.S. It is a structure with other fields (not shown here) not a matrix
What I have been doing is
Tot=0;
for i=1:S.numElements
if S.a(i).field1 == 1
Tot=Tot+S.a(i).field2;
end
end
Avg= Tot/S.numElementsBis (I have this value stored in another field)

Respuesta aceptada

Guillaume
Guillaume el 2 de Mzo. de 2016
It's not clear if your S is a structure array with scalar fields:
S = struct('a', {2; 0; 1; 2}, 'b', {4; 6; 5; 3})
meanb = mean([S([S.a] == 2).b])
Or a scalar structure with fields of arrays:
S = struct('a', [2; 0; 1; 2], 'b', [4; 6; 5; 3])
meanb = mean(S.b(S.a == 2))
Either way as illustrated above getting the mean is easy.
  5 comentarios
Guillaume
Guillaume el 2 de Mzo. de 2016
|| is a short-circuit logical operator (it does not evaluate the second argument if the first is true), it only works with scalar.
With vectors, you have to use | (single bar).
etudiant_is
etudiant_is el 2 de Mzo. de 2016
Thanks, with this it works

Iniciar sesión para comentar.

Más respuestas (0)

Community Treasure Hunt

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

Start Hunting!

Translated by