计数的平均值

时间:2014-04-07 20:51:56

标签: matlab vector average

这可能听起来太微不足道但我对以下逻辑感到困惑。我有一个长度为D = [1 1.2 4 5 1.9 0 9 0.8 1.13 3]的向量M= 10。我需要记录向量D的距离计数,该距离小于等于2.因此,count =(1,2,3 ......等),即离散。然后我需要找到Avg_Count = 1\M sum_i=1 to M count_i

的平均值

以下代码是否正确?

D = [1 1.2 4 5 1.9 0 9 0.8 1.13 3];

count = 0;
for I = 1:M
if (D(I)<=2) 
count = count+1;
end

Avg_count = mean(count);

混淆是计数只包含一个数字,单个数字的平均值本身。我如何实现上述逻辑?谢谢。

3 个答案:

答案 0 :(得分:1)

现在您已经提供了所需输出的示例,我想我明白了您的需求(至少对于计数部分;我不确定平均值):

count = zeros(size(D));
ind = D<=2; %// logical index
count(ind) = 1:nnz(ind); %// fill values indexed by ind
Avg_count = mean(count);

答案 1 :(得分:1)

D = [1 1.2 4 5 1.9 0 9 0.8 1.13 3];

count = zeros(size(D));

running_total = 0;

for i = 1:size(D,2)
    if D(i) < 2
        running_total = running_total + 1;
        count(i) = running_total;
    end
end

Avg_count = mean(count);

count =

   1   2   0   0   3   4   0   5   6   0

Avg_count =  2.1000

答案 2 :(得分:1)

试试这个 -

D = [1 1.2 4 5 1.9 0 9 0.8 1.13 3]
out = cumsum(D<2) .* (D<2)
mean_value = mean(out)

输出 -

out =
     1     2     0     0     3     4     0     5     6     0

mean_value =
    2.1000