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 Center および File ExchangeMATLAB についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by