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)?
댓글 수: 0
채택된 답변
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 Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!