How to count the number of consecutive identical elements (in both the directions) in a binary vector ?

33 ビュー (過去 30 日間)
Suppose I have a binary vector
X = [0 0 0 0 1 1 1 0 1 1 1 1]
I want to characterize each element with the number of identical elements occurring in consecutive positions in both the directions. For instance, the desired output should look like:
Y = [4 4 4 4 3 3 3 1 4 4 4 4].
I found a similar thread, but it counts only in the forward direction. Thanks in advance for any sort of assistance.
  1 件のコメント
Guillaume
Guillaume 2018 年 2 月 11 日
I'm not sure I understand the concept of direction for identical consecutive elements. Identity is not directional.

サインインしてコメントする。

採用された回答

Jan
Jan 2018 年 2 月 11 日
編集済み: Jan 2018 年 2 月 11 日
X = [0 0 0 0 1 1 1 0 1 1 1 1];
[B, N] = RunLength(X);
Y = RunLength(N, N);
If you do not have a C-compiler for the fast C-Mex function, use RunLength_M.
Or with Matlab code:
d = [true, diff(X) ~= 0, true]; % TRUE if values change
n = diff(find(d)); % Number of repetitions
Y = repelem(n, n)
  2 件のコメント
Jos (10584)
Jos (10584) 2018 年 2 月 11 日
編集済み: Jos (10584) 2018 年 2 月 11 日
the use of repelem is clever indeed!

サインインしてコメントする。

その他の回答 (2 件)

Jos (10584)
Jos (10584) 2018 年 2 月 11 日
編集済み: Jos (10584) 2018 年 2 月 11 日
Something like this?
X = [0 0 0 0 1 1 1 0 1 1 1 1] % row vector!
numX = numel(X) ;
Q = find([false diff(X)0]) ;
I = zeros(1, numX) ;
I(Q) = 1 ;
I = cumsum(I) ;
N = diff([1 Q numX+1]) ;
result = N(I+1)

Image Analyst
Image Analyst 2018 年 2 月 11 日
Here's yet another way:
X = logical([0 0 0 0 1 1 1 0 1 1 1 1])
Y = zeros(1, length(X)); % Initialize output as the same size as X.
props = regionprops(X, 'Area', 'PixelIdxList');
for k = 1 : length(props)
Y(props(k).PixelIdxList) = props(k).Area;
end
props = regionprops(~X, 'Area', 'PixelIdxList');
for k = 1 : length(props)
Y(props(k).PixelIdxList) = props(k).Area;
end

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by