How can I find run length consecutive ones and zeros and their occurrence times in a binary sequence in MATLAB?

19 views (last 30 days)

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
You can use the TEXTSCAN function by specifying delimiters and then use LENGTH function to find the length of each sequence. After that, you can compute the number of occurrences with HIST function as in the example below:
%Creating a binary sequence in a string with no spaces
s = [1 1 0 0 0 0 0 1 1 1 1 0 1 1 0 1 1 0 1 1 1 0 1 0 1 0 1 0 0 1 1 1];
s = sprintf('%d',s);
%Reading the consequences of 1's from the string by using 0's as delimiters
t1=textscan(s,'%s','delimiter','1','multipleDelimsAsOne',1);
% Converting cell array of cell into a single cell array
d = t1{:};
% Computing the length of each run by going through the array and assigning
% it into
for k = 1:length(d)
data(k) = length(d{k});
end
% Using histogram function to compute the number of times for each length
[number_times run_length] = hist(data, [1:max(data)])
To do the same operation for finding run lengths and frequencies of "zeros" instead of "'ones", change the delimiter in the TEXTSCAN function to be '1' instead of '0'.

More Answers (1)

Jan
Jan on 8 Jan 2018
Edited: Jan on 8 Jan 2018
s = [1 1 0 0 0 0 0 1 1 1 1 0 1 1 0 1 1 0 1 1 1 0 1 0 1 0 1 0 0 1 1 1];
[B, N] = RunLength(s);
Or with M-code:
d = [true; diff(s(:)) ~= 0]; % TRUE if values change
B = x(d); % Elements without repetitions
k = find([d', true]); % Indices of changes
N = diff(k); % Number of repetitions
Now B is the value and N the number of repetitions.
This is easier and more efficient than converting the data to a string, running textscan and counting the length of the output in a loop.

Tags

Products

Community Treasure Hunt

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

Start Hunting!