I want to find out whether there are repetitive values (minimum of 4 or above) in a row.

1 回表示 (過去 30 日間)
I am printing an array which contains only 1 and 0. I want to find out whether there are repetitive values (minimum of 4 or above) in a row. For example: 10111101 - 1 is repeated 4 times or 0100000110 - 0 is repeated 5 times.
I tried using a couple of algorithms and functions like RLE (run length encoding) and RL (run length), but they don't seem to work. Unless I am coding it incorrectly. Could you please suggest method which I could use?
Thank you.

採用された回答

Walter Roberson
Walter Roberson 2021 年 2 月 12 日
編集済み: Walter Roberson 2021 年 2 月 12 日
runs_zero = strfind([1 YourArray], [1 0 0 0 0])
runs_one = strfind([0 YourArray], [0 1 1 1 1])
The results will be the positions in YourArray where runs of 4 or more zeros start, or runs of 4 or more 1's start. In both cases, the indices will be of the start of the run.
The code takes care to be able to detect runs at the very beginning of the array.
This code assumes the array is a row vector, and will fail for column vector.

その他の回答 (1 件)

Aditya Kommajosula
Aditya Kommajosula 2021 年 2 月 12 日
Hi Jesvin,
I understand you are only trying to detect occurrences of consecutive bits of length at least 4, and not count them in the input array.
Assuming an input character vector for the binary representation, the following might be something to try:
s1 = '101111001';
contains(s1,'0000') || contains(s1,'1111') % returns 'true'
s2 = '101110001';
contains(s2,'0000') || contains(s2,'1111') % returns 'false'
In case the input representation is a 1D numeric array, you could modify the above with:
contains(sprintf('%d', arr),'0000') || contains(sprintf('%d', arr),'1111') % where 'arr' is the input array
Please note that starting R2016b, 'contains' is recommended over 'strfind' for finding patterns within string arrays (https://www.mathworks.com/help/matlab/ref/strfind.html).
Thanks and regards
  1 件のコメント
Walter Roberson
Walter Roberson 2021 年 2 月 13 日
strfind has an undocumented availability to work with numeric or logical arrays that is very useful.

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

カテゴリ

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