Effacer les filtres
Effacer les filtres

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

9 vues (au cours des 30 derniers jours)
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)?

Réponse acceptée

Bruno Luong
Bruno Luong le 19 Déc 2018
Modifié(e) : Bruno Luong le 19 Déc 2018
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)'

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by