Finding the numbers of a vector with the same length?

1 回表示 (過去 30 日間)
Boris
Boris 2012 年 11 月 14 日
Dear all
Assuming there is a vector consisting only 0 and 1 like:
x=[0 1 1 0 1 0 0 1 1 1 0 1 0 1 1 1 0 1 1 0 1 1 0 1]
I want to figure out how many times 1 or 1 1 or 1 1 1 or even longer 1 in a row exists are in this vector?
The solution here would be:
nr_1= 3
nr_1_1= 3
nr_1_1_1= 2
nr_1_1_1_1 = 0
....
Is there a easy way to do it?
Thanks for your help
(Matlab 2010a)

採用された回答

C.J. Harris
C.J. Harris 2012 年 11 月 14 日
rep=diff(find(diff([-Inf x Inf])));
val=x(cumsum(rep));
out = hist(rep(val == 1), max(rep));
  2 件のコメント
Boris
Boris 2012 年 11 月 15 日
The main disadvantages about this solution is, that you will get a lot of zeros in the out-vector. Otherwise, it works well. Thanks a lot
C.J. Harris
C.J. Harris 2012 年 11 月 15 日
You can process the out data if you want to remove the zeros, for example:
[out(find(out ~= 0)); find(out ~= 0)]
This will then show occurrences (top row) and sequence length (bottom row).

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

その他の回答 (2 件)

Matt Fig
Matt Fig 2012 年 11 月 14 日
編集済み: Matt Fig 2012 年 11 月 14 日
Here's another solution:
D = diff(find([1 ~x 1]))-1;
D = histc(D,1:max(D))
  2 件のコメント
Andrei Bobrov
Andrei Bobrov 2012 年 11 月 15 日
+1
Boris
Boris 2012 年 11 月 15 日
Works well. Thanks a lot.

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


Harshit
Harshit 2012 年 11 月 14 日
Hi,
You can save zero as it is and whenever 1 appears start a counter and count the number of 1s in succession. It is Run length encoding. When done just count the number of times the numbers appears.

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by