仅查找所选条目的平均值 [英] Finding mean of selected entries only
问题描述
考虑两个向量:
v= [1 2 3 4 5 6 7]
a=['a' 'b' 'c' 'a' 'a' 'a' 'd']
我想查找v中所有条目的均值,其中a中的对应条目为'a';
I want to find the mean of all entries in v whose corresponding entries in a is 'a';
即test =平均值(1,3,4,5)
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 = 1 0 0 4 5 6
问题:
- 它为未找到的条目分配0
- 它不在考虑上学期
推荐答案
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
将您的test
向量形成为逻辑数组,并在向量中找到字符'a'的位置分配1,在没有向量的地方分配0:
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
然后您可以将其用作逻辑索引,以从向量v
中提取相应的条目:
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
在要测试是否存在多个字符的情况下很有用,例如,如果要查找'a'或'b'所在的位置.
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.
这篇关于仅查找所选条目的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!