MATLAB: Replace numbers in a matrix that are surrounded in 8-directions by NaNs to NaNs

hole fillingimage processingmaskingMATLAB

Hi community,
I have several matrices containing 0s, 1s and NaNs. Most of elements are 0s and NaNs, and in less amount there are 1s.
Regarding 1s, I need to replace them to NaNs if they are surrounded in 8 directions by NaNs. These 1s are not single 1s, but can be also be connected in 8-directions.
For example, considering this matrix:
[NaN NaN NaN NaN 1 0;NaN 1 NaN NaN 1 0;NaN NaN 1 NaN 1 0;NaN NaN 1 NaN NaN 0;NaN NaN NaN NaN NaN 0]
The expected output would be:
[NaN NaN NaN NaN 1 0;NaN NaN NaN NaN 1 0;NaN NaN NaN NaN 1 0;NaN NaN NaN NaN NaN 0;NaN NaN NaN NaN NaN 0]
Thank you very much for your help!!

Best Answer

Try imfill(), then mask:
% Create input matrix.
m = [NaN NaN NaN NaN 1 0;NaN 1 NaN NaN 1 0;NaN NaN 1 NaN 1 0;NaN NaN 1 NaN NaN 0;NaN NaN NaN NaN NaN 0]
% Create initial mask
nanLocations = isnan(m)
% Fill holes in mask.
mask = imfill(nanLocations, 'holes')
% Create output matrix.
output = m; % Initialize
output(mask) = nan % This will assign nan to filled holes.