Effacer les filtres
Effacer les filtres

Determine if binary vector transitions from 1 to 0 to 1 again?

4 vues (au cours des 30 derniers jours)
shane
shane le 6 Nov 2015
Modifié(e) : Jan le 7 Nov 2015
Say I have a binary marix:
M = [1 1 1 1; 1 1 1 0; 1 1 0 1; 1 0 1 1; 1 1 0 0; 1 0 0 1; ...]
I want to eliminate the rows where there are any 0 'islands' in the middle of 1's. So in the above matrix I want to eliminate rows 3, 4, 6. If the rows were longer it wouldn't matter how many islands there are, e.g. [1 0 1 1 1 1 0 0 1] would be removed.
The answer given in the question below is related, but I am struggling in applying it to this problem. Some combination of diff() and cumsum() are needed I think. Thanks!
  1 commentaire
shane
shane le 6 Nov 2015
Modifié(e) : shane le 6 Nov 2015
Any thoughts?
I made a little progress: In diff(M,1,2), undesirable rows will always have -1 then 1 (reading from left to right), with any number of zeros in between. But the problem then becomes to issolate this pattern, as the number of zeros varies, and there are any number of leading and trailing numbers. If you could ignore the zeros in between then in the next iteration of diff() undesirable rows would exclusively contain a 2.
But how do you ignore the zeros in between? And how do you isolate this pattern from the leading and trailing numbers?

Connectez-vous pour commenter.

Réponses (1)

shane
shane le 6 Nov 2015
Modifié(e) : Jan le 7 Nov 2015
In case anyone is interested, here's one solution, couldn't avoid a loop across the columns:
M = [1 1 1 1; 1 1 1 0; 1 1 0 1; 1 0 1 1; 1 1 0 0; 1 0 0 1];
ones = double(diff(M, 1, 2)==1); %matrix of ones
neg_ones = double(diff(M, 1, 2)==-1); %matrix of negative ones
ones(ones==0) = nan; %replace 0 with nan
neg_ones(neg_ones==0) = nan; %replace 0 with nan
I_remove = zeros(size(M, 1), 1); %initialize I_remove
for i = 1:size(M, 2)-1 %loop to slide ones matrix across neg_ones matrix
I_remove = any(I_remove + any(ones(:,1+i:end) + neg_ones(:,1:end-i), 2), 2); %update row index
end
M = M(~I_remove,:); %remove not wanted rows

Catégories

En savoir plus sur Resizing and Reshaping Matrices 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