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

조회 수: 7 (최근 30일)
I would like to find run length of consecutive ones and zeros in a binary sequence and the number of times each length occurs.

채택된 답변

MathWorks Support Team
MathWorks Support Team 2009년 6월 27일
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
Jan
Jan 2018년 1월 8일
The loop for k = 1:length(d), data(k) = length(d{k}); end can be replaced by the more efficient:
data = cellfun('length', d);

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2018년 1월 8일
편집: Jan 2018년 1월 8일
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.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by