필터 지우기
필터 지우기

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

조회 수: 4 (최근 30일)
shane
shane 2015년 11월 6일
편집: Jan 2015년 11월 7일
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
shane
shane 2015년 11월 6일
편집: shane 2015년 11월 6일
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?

댓글을 달려면 로그인하십시오.

답변 (1개)

shane
shane 2015년 11월 6일
편집: Jan 2015년 11월 7일
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

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by