number of times consecutive values occur

2 ビュー (過去 30 日間)
NMans
NMans 2018 年 3 月 22 日
コメント済み: NMans 2018 年 3 月 28 日
I have a row vector (1000 x 1) containing the values of 0 and nonzero values. I would like to find the number of times non-zero value occurs consecutively but with conditions - 2 consecutive of non-zero, 3 consecutive of non-zero, 4 consecutive of non-zero and so on (probably up to 100).
So for example I have X = [ 1 1 1 1 0 1 1 0 1 1 0 1 1 0 0 1 1 1]. The number of times 1 occurs 2-consecutively is 3. The number of times 1 occurs 3-consecutively is 1. The number of times 1 occurs 4-consecutively is 1.
I'm not sure how to tackle this.

採用された回答

Stephen23
Stephen23 2018 年 3 月 22 日
編集済み: Stephen23 2018 年 3 月 22 日
Using basic MATLAB commands:
>> X = [ 1 1 1 1 0 1 1 0 1 1 0 1 1 0 0 1 1 1];
>> D = diff([0,X,0]);
>> V = find(D<0)-find(D>0);
>> U = unique(V) % lengths
U =
2 3 4
>> histc(V,U) % number of occurrences
ans =
3 1 1
  1 件のコメント
NMans
NMans 2018 年 3 月 28 日
Thanks! This works!

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2018 年 3 月 22 日
編集済み: Jan 2018 年 3 月 22 日
X = [1 1 1 1 0 1 1 0 1 1 0 1 1 0 0 1 1 1];
[B, N] = RunLength(X);
N(B == 0) = []; % Ignore the zeros
[R, Edge] = histcounts(N, 'BinMethod', 'Integers')
Or with a 2nd RunLength:
[B, N] = RunLength(X);
[V, R] = RunLength(sort(N(B ~= 0)))
Now the V(i) repetitions occurs R(i) times.
If you do not have a C-compiler installed, use RunLength_M from this submission instead.
  3 件のコメント
Jan
Jan 2018 年 3 月 27 日
@NMans: See the example above. Replace "RunLength" by "RunLength_M".
NMans
NMans 2018 年 3 月 28 日
Thanks!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMATLAB Coder についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by