MATLAB Answers

SS
1

Mean based on positive and negative values of a field

Asked by SS
on 29 Aug 2019
Latest activity Commented on by SS
on 30 Aug 2019
I have a structure S (10000 X 1) with 10 fields. I want to calculate (two) means and standard deviations of one particluar field f1. I have condition on field f2.
mean_1 and SD_1: consider the values of f1 (in calculation of mean and SD) if, f2 is positive.
mean_2 and SD_2: consider the values of f1 (in calculation of mean and SD) if, f2 is negative.
Any smart way to do this?

  0 Comments

Sign in to comment.

1 Answer

Answer by Rik
on 29 Aug 2019
 Accepted Answer

Logical indexing:
L=[S.f2]>0;
pos_mean=mean([S( L).f1]);
neg_mean=mean([S(~L).f1]);

  7 Comments

S=struct;
S(1).f1=[2,3,4,5,6,7,8,10,14,16,18,20];
S(1).f2=[-3,6,9,-12,15,18,-21,24,27,-30,33,-36];
S(2).f1=[4,5,6,7,8];
S(2).f2=[-0.1, 4,0.8,-3,4];
Something like this. When, I tried to adapt the above syntax to this structure array it gives the follwing error:
"The logical indices contain a true value outside of the array bounds."
As I mentioned, non-scalar structs complicate it a bit.
all_f1=[S.f1];
all_f2=[S.f2];
L=all_f2>0;
pos_mean=mean(all_f1( L));
neg_mean=mean(all_f1(~L));
Note that the concatenation will probably not work if your fields have a different direction than your struct array. So this should work, but a 100X1 struct array with 1Xn fields will not.
Great, thanks.

Sign in to comment.