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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by