计算向量中连续1和0的数量

时间:2013-09-08 13:02:48

标签: matlab

在Matlab中我有一个看起来像这样的矢量:

0 0 1 1 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 1 0 1

我现在要做的是计算此向量中的1的数量。连续1计为1.此外,我还想计算1之间的0的平均数和中位数。所以对于这个例子:

1s:5

中位数0:3.5

平均0:3

我用蛮力方法解决了这个问题,即研究循环中的每个元素并检查前一个元素和下一个元素。但我确信必须有一个更快的解决方案。有什么想法吗?

3 个答案:

答案 0 :(得分:3)

给出向量v中的数据,

v = [ 0 0 1 1 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 1 0 1 ]; % data

计算如下:

w = [ 1 v 1 ]; % auxiliary vector
runs_zeros = find(diff(w)==1)-find(diff(w)==-1); % lenghts of runs of 0's

% Desired results:
number_ones = length(runs_zeros)-1+v(1)+v(end);
% For average and median, don't count first run if v(1) is 0,
% or last run if v(end) is 0:
average_runs_zeros = mean(runs_zeros(2-v(1):end-1+v(end))); 
median_runs_zeros = median(runs_zeros(2-v(1):end-1+v(end)));

这比@ TryHard的解决方案更快,因为它不需要转换为字符串

答案 1 :(得分:1)

好的,所以这似乎正在发挥作用

>> a=[0 0 1 1 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 1 0 1];
>> %Remove traling and leading zeros
>> y = a(find(a,1,'first'):find(a,1,'last'));
>> q = diff([0 a 0] == 1);
>> v = find(q == -1) - find(q == 1);
>> length(v) % Consecutive Ones
ans =

     5

>> q = diff([0 ~y 0] == 1);
>> v = find(q == -1) - find(q == 1);
>> v

v =

     3     4     4     1

>> median(v)

ans =

    3.5000

>> mean(v)

ans =

    3

答案 2 :(得分:0)

您可以按照以下方式执行此操作:

dat=[0 0 1 1 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 1 0 1];
str = regexprep(num2str(dat),' ','');
[n1 istart1 iend1] = regexp(str,'[1]+','match','start','end');
[n0 istart0 iend0] = regexp(str(min(istart1):max(iend1)),'[0]+','match','start','end');

% number of strings of `1`s
length(n1)

% property of intercalated strings of `0`s
median([iend0-istart0+1])
mean([iend0-istart0+1])