MATLAB: Replace a number in a matrix depending on neighbor numbers

MATLABmatrixmatrix arraymatrix manipulation

Hi all,
Let say I have this matrix:
[NaN NaN NaN NaN NaN NaN NaN;NaN 2 2 2 2 2 NaN;NaN 2 1 1 1 2 NaN;NaN 2 1 2 1 2 NaN;NaN 2 1 1 1 2 NaN;NaN 2 2 2 2 2 NaN;NaN NaN NaN NaN NaN NaN NaN]
I would like to replace all numbers 2 that are neighbor to NaN by NaN, the result I want is:
[NaN NaN NaN NaN NaN NaN NaN;NaN NaN NaN NaN NaN NaN NaN;NaN NaN 1 1 1 NaN NaN;NaN NaN 1 2 1 NaN NaN;NaN NaN 1 1 1 NaN NaN;NaN NaN NaN NaN NaN NaN NaN;NaN NaN NaN NaN NaN NaN NaN]
I´m quite new to Matlab. Any idea about how to do this replacements?. There is a number 2 right in the center of the 7×7 array that I don´t want to loose, as this number is surrounded only by 1´s.
Thank you very much for your help!.

Best Answer

It is unclear if elements connected diagonally count as neighbours. If not, then you could try something like this.
%%Work with At to keep A intact
At=A;
%%Replace NaN with some number
At(isnan(At))=9;
%%B is for saving index of new NaNs
B=zeros(size(At));
%%Find sequences of [2 NaN] and [NaN 2] row-wise
for i=1:size(At,1)
B(i,strfind(At(i,:),[9 2])+1)=NaN;
B(i,strfind(At(i,:),[2 9]))=NaN;
end
%%Transpose A and repeat (same as column-wise)
At=At';
for i=1:size(At,2)
B(strfind(At(i,:),[9 2])+1,i)=NaN;
B(strfind(At(i,:),[2 9]),i)=NaN;
end
A(isnan(B))=NaN
ans =
NaN NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN
NaN NaN 1 1 1 NaN NaN
NaN NaN 1 2 1 NaN NaN
NaN NaN 1 1 1 NaN NaN
NaN NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN