How can I find run length consecutive ones and zeros and their occurrence times in a binary sequence in MATLAB?
7 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
MathWorks Support Team
il 27 Giu 2009
Commentato: Image Analyst
il 28 Feb 2020
I would like to find run length of consecutive ones and zeros in a binary sequence and the number of times each length occurs.
Risposta accettata
MathWorks Support Team
il 27 Giu 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'.
1 Commento
Jan
il 8 Gen 2018
The loop for k = 1:length(d), data(k) = length(d{k}); end can be replaced by the more efficient:
data = cellfun('length', d);
Più risposte (1)
Jan
il 8 Gen 2018
Modificato: Jan
il 8 Gen 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.
Vedere anche
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!