How to eliminate standalone 1 or 0 in binary matrix
이전 댓글 표시
Hello
I have large binary matrices (order 30000 x 5000 values) in which I have to eliminate stand-alone 1's or 0's.
E.g. when a row looks like this: 0 0 1 1 1 0 1 1 0 0 1 0 1 1 1
It should be adapted to: 0 0 1 1 1 1 1 1 0 0 0 0 1 1 1
Or thus, when there's only one 1 between some 0's or one 0 between some 1's, it should be changed to a 0 or 1 respectively.
I have no clue how to do this except from running through the entire matrix and keeping count of the length of the series of 1's or 0's - which seems utterly inefficiënt to me. Any ideas on functions or better ways to tackle this? Thanks!
채택된 답변
추가 답변 (1개)
Setsuna Yuuki.
2020년 11월 23일
편집: Setsuna Yuuki.
2020년 11월 23일
You only need a loop and correct conditional statement, the conditional can be:
if(A(n) ~= A(n+1) && A(n) ~= A(n-1) && A(n) == 1)
A(n) = 0;
elseif(A(n) ~= A(n+1) && A(n) ~= A(n-1) && A(n) == 0)
A(n) = 1;
end
so you compare only with the previous bit and the next.
댓글 수: 5
Rik
2020년 11월 23일
Matlab is fast when using loops, but I would not encourage people to use loops for arrays with 600 million elements.
Setsuna Yuuki.
2020년 11월 23일
Thanks for your advice, I learn a lot from your answers
Simon Allosserie
2020년 11월 24일
Rik
2020년 11월 24일
This code can be simplified (or at least be edited to remove duplicated code):
%option 1:
sz=size(A);
for m = 1:sz(1)
for n=1:sz(2)
if ...
( n==1 && ...
(A(m,n) ~= A(m,2 ) && A(m,n) ~= A(m,3 )) ) || ...
( n==sz(2) && ...
( A(m,n) ~= A(m,end-1)) ) || ...
( ( n~=1 && n~=sz(2) ) && ...
(A(m,n) ~= A(m,n+1) && A(m,n) ~= A(m,n-1 )) )
A(m,n) = abs(A(m,n)-1);
end
end
end
%option 2:
sz=size(A);
for m = 1:sz(1)
for n=1:sz(2)
if n==1
L = (A(m,n) ~= A(m,2 ) && A(m,n) ~= A(m,3 )) ;
elseif n==sz(2)
L = A(m,n) ~= A(m,end-1)) ;
else
L = (A(m,n) ~= A(m,n+1) && A(m,n) ~= A(m,n-1 )) ;
end
if L
A(m,n) = abs(A(m,n)-1);
end
end
end
Setsuna Yuuki.
2020년 11월 24일
I did it this way:
A = [0 0 1 1 1 0 1 1 0 ;0 0 0 1 0 1 0 1 1]';
[r,c,~]=size(A);
A = reshape(A,[1, r*c]);
for n = 2:r*c-1
if(A(n) ~= A(n+1) && A(n) ~= A(n-1) && A(n) == 1)
A(n) = 0;
elseif(A(n) ~= A(n+1) && A(n) ~= A(n-1) && A(n) == 0)
A(n) = 1;
end
end
A = reshape(A,[r,c])';
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!