Find indices where runs of zeros and ones ends

3 ビュー (過去 30 日間)
Awais Saeed
Awais Saeed 2021 年 8 月 3 日
編集済み: Stephen23 2021 年 8 月 4 日
Assuming that I have a vector
H = [0 0 0 0 1 1 1 1 0 1 0 1 0 0 0 0 0];
I want to know the indices where long runs of 1's and 0's ends. Let's say if a bit repeats 4 times or greater, then it is a run of length greater than 4. According to this, I want to know the indices where all runs ends. First run is of zeros which ends at index 4. Second run is of ones which ends at 8. Third run is of zeros again and it ends at 17.
So far, I am able to count the run length only as following
i = find(diff(H));
run_length = [i numel(H)] - [0 i];
run_length =
4 4 1 1 1 1 5
However, the needed answer is [4 8 17]. cumsum would not work because it will give cummulative sum of whole vector as
cumsum(run_length)
ans =
4 8 9 10 11 12 17
Any suggestions will be helpful.

採用された回答

Jonas
Jonas 2021 年 8 月 3 日

i would use

H = [0 0 0 0 1 1 1 1 0 1 0 1 0 0 0 0 0];
Hstr=erase(num2str(H),' ');
[~,onesEnds]=regexp(Hstr,{'0000+','1111+'});
sort(cell2mat(onesEnds))
  4 件のコメント
Awais Saeed
Awais Saeed 2021 年 8 月 4 日
Yes, this one is more flexible. Thank you.
Stephen23
Stephen23 2021 年 8 月 4 日
編集済み: Stephen23 2021 年 8 月 4 日
Simpler and more efficient:
H = [0,0,0,0,1,1,1,1,0,1,0,1,0,0,0,0,0];
S = sprintf('%u',H);
X = regexp(S,'(0{4,}|1{4,})','end') % only zeros and ones
X = 1×3
4 8 17
X = regexp(S,'(.)(??$1{3,})','end') % any character
X = 1×3
4 8 17

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

その他の回答 (0 件)

カテゴリ

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