How to count the number of consecutive identical element of each row in a binary matrix?
10 次查看(过去 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!