フィルターのクリア

How to count the number of consecutive identical element of each row in a binary matrix?

9 ビュー (過去 30 日間)
Matrix A contains only binary numbers: A=[0,0,0,0,1,1,0,0;1,0,1,1,1,1,0,0;0,1,1,0,1,0,0,1]
A = 0 0 0 0 1 1 0 0
1 0 1 1 1 1 0 0
0 1 1 0 1 0 0 1
I want to count the number of consecutive elements of each row (use first row as an example) in this way:
[1st consecutive 0, 2nd consecutive 0, 3rd consecutive 0, 4th consecutive 0, 1st consecutive 1, 2nd consecutive 1, 1st consecutive 0, 2nd consecutive 0]
So the output is
B = 1 2 3 4 1 2 1 2
1 1 1 2 3 4 1 2
1 1 2 1 1 1 2 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The methods I found are all for an array:
For example:
A= [0,0,0,0,1,1,0,0];
i = find(diff(A)) ;
n = [i numel(A)] - [0 i];
c = arrayfun(@(X) 1:X, n , 'un',0);
B = cat(2,c{:})
Output is
B = 1 2 3 4 1 2 1 2
How can I do this for a matrix (without using for)?

採用された回答

Bruno Luong
Bruno Luong 2018 年 12 月 19 日
編集済み: Bruno Luong 2018 年 12 月 19 日
A = [0 0 0 0 1 1 0 0;
1 0 1 1 1 1 0 0;
0 1 1 0 1 0 0 1]
m = size(A,1);
B = A';
b = [true(1,m); diff(B)~=0];
[r,~] = find(b);
B(~b) = 1;
B(b) = [1; 1-diff(r)];
B(1,:) = 1;
B = cumsum(B)'

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by