MATLAB: How to eliminate standalone 1 or 0 in binary matrix

binaryfindMATLABmatrix manipulation

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!

Best Answer

I would suggest using a convolution with a flat kernel.
kernel=ones(1,3,1);kernel=kernel/sum(kernel(:));
A=[0 0 1 1 1 0 1 1 0 0 1 0 1 1 1];
B=convn(A,kernel,'same');
C=round(B);
clc,disp([A;B;C])%display the original, the convolution result and the final output
0 0 1.0000 1.0000 1.0000 0 1.0000 1.0000 0 0 1.0000 0 1.0000 1.0000 1.0000 0 0.3333 0.6667 1.0000 0.6667 0.6667 0.6667 0.6667 0.3333 0.3333 0.3333 0.6667 0.6667 1.0000 0.6667 0 0 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 0 0 0 1.0000 1.0000 1.0000 1.0000
Note that the [0 0 1 0 1 1] is changed to [0 0 0 1 1 1]. If you don't want that, you can change the kernel to something like this:
kernel=[1 1 1 0 0];kernel=kernel/sum(kernel(:));