pac
pac

Reputation: 291

Finding mean of selected entries only

Consider the two vectors:

 v= [1 2 3 4 5 6 7]

 a=['a' 'b' 'c' 'a' 'a' 'a' 'd']

I want to find the mean of all entries in v whose corresponding entries in a is 'a';

i.e. test= mean(1,3,4,5)

I have tried this for a start to catch the entries:

for i=1:7
 if abs(char(a(i))-char(c))==0;
   test(i)=v(i);
 end
end

test

test =      1     0     0     4     5     6  

PROBLEMS:

  1. It is assigning 0 for entries not found
  2. It is not considering last term

Upvotes: 1

Views: 422

Answers (1)

Bill Cheatham
Bill Cheatham

Reputation: 11937

Try using the ismember function:

>> help ismember
 ismember True for set member.
    ismember(A,S) for the array A returns an array of the same size as A
    containing 1 where the elements of A are in the set S and 0 otherwise.
    A and S can be cell arrays of strings.

ismember forms your test vector as a logical array, assigning 1 where the character 'a' is found in your vector, and 0 where it isn't:

>> ismember(a, 'a')

ans =

 1     0     0     1     1     1     0

You can then use this as a logical index to extract the corresponding entries from your vector v:

>> v(ismember(a, 'a'))

ans =

     1     4     5     6

Finally, you can take the mean of this vector:

>> mean(v(ismember(a, 'a')))

ans =

  4

EDIT I have realised that in your case, you can actually form your logical array in a much simpler way, using a comparison operator:

>> a == 'a'

ans =

     1     0     0     1     1     1     0

So your final line of code will look like so:

>> mean(v(a == 'a'))

ans =

     4

ismember is useful where you want to test for the presence of more than one character, for example if you wanted to find locations where 'a' or 'b' were.

Upvotes: 1

Related Questions