计算向量中连续的1和0的数目 [英] Count numbers of consecutive 1s and 0s in a vector

查看:135
本文介绍了计算向量中连续的1和0的数目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Matlab I have a vectors that looks like this:

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

我现在要做的是计算此向量中的1的数量.连续的1s计为1.此外,我还想计算1s之间的0s的平均值和中位数.因此,对于此示例:

What I want to do now is to count the number of 1 in this vector. Consecutive 1s count as 1. Additionally, I want also to calculate the average and median numbers of 0s between 1s. So for this example:

1秒:5

中位数0:3.5

平均0:3

我用蛮力方法解决了这一问题,即研究循环中的每个元素并检查上一个和下一个元素.但我敢肯定,必须有一个速度更快的解决方案.有什么主意吗?

I solved that with a brute force method, that is investigate each element in a loop and check the previous as well as the next element. But I'm sure there has to be a solution that is way faster. Any idea?

推荐答案

给出向量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的解决方案要快,因为它不需要转换为字符串

This is faster than @TryHard's solution because it doesn't require converting to strings

这篇关于计算向量中连续的1和0的数目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆