MATLAB: Average of field in a structure with an if condition

average structure with nested if

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)

Best Answer

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.
Related Question