Finding mean of selected entries only

∥☆過路亽.° 提交于 2019-12-24 08:48:33

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/10070176/finding-mean-of-selected-entries-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!