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

类别

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