Find the longest streak of 1's from a vector

1 回表示 (過去 30 日間)
Vic
Vic 2014 年 11 月 27 日
コメント済み: Image Analyst 2014 年 11 月 27 日
Suppose I have a vector of 0's and 1's. How can I find, without for-loop(s), the longest streak of 1's in that vector?
eg. For the vector v=[0,1,0,0,1,1,0,0, 1,1,1,1,1 ,0,1,0,1], I want codes that return: longest streak=5, location=9 .
Any suggestion? Thanks in advance.

採用された回答

Guillaume
Guillaume 2014 年 11 月 27 日
I'm sure if you search cody you'll find a few of this type of problem. A combination of diff and find should do the trick. For example,
v=[0,1,0,0,1,1,0,0, 1,1,1,1,1 ,0,1,0,1];
vd = diff([0 v 0]); %the 0s ensure that there's always a pair of [+1 -1] in the diff
starts = find(vd == 1);
ends = find(vd == -1);
[longest_streak, idx] = max(ends-starts);
location = starts(idx);
  2 件のコメント
Vic
Vic 2014 年 11 月 27 日
thanks a lot.
Image Analyst
Image Analyst 2014 年 11 月 27 日
Vic, you can also do it with regionprops() in the Image Processing Toolbox as an alternate method. Not sure it would be any fewer lines of code though.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by