I want to find out whether there are repetitive values (minimum of 4 or above) in a row.
1 view (last 30 days)
Show older comments
Jesvin Jose
on 12 Feb 2021
Commented: Walter Roberson
on 13 Feb 2021
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.
0 Comments
Accepted Answer
Walter Roberson
on 12 Feb 2021
Edited: Walter Roberson
on 12 Feb 2021
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.
More Answers (1)
Aditya Kommajosula
on 12 Feb 2021
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 Comment
Walter Roberson
on 13 Feb 2021
strfind has an undocumented availability to work with numeric or logical arrays that is very useful.
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!