function y=nghbrfilt(x)
%y=nghbrfilt(x)
%
%nearest neighbor filter for a matrix.
%uses the median value the set determined by the (i,j)
%element of a matrix and its 4 neighbors


[M,N]=size(x);

y=nan*ones(M,N);

%%%%% do the corners
y(1,1)=nanmedian([x(1,1),x(1,2),x(2,1)]);
y(1,N)=nanmedian([x(1,N),x(1,N-1),x(2,N)]);
y(M,1)=nanmedian([x(M,1),x(M-1,1),x(M,2)]);
y(M,N)=nanmedian([x(M,N),x(M-1,N),x(M,N-1)]);

%%%%% do the rest of the sides

i=2:M-1;
j=2:N-1;


y(1,j)=nanmedian([x(1,j);x(1,j+1);x(1,j-1);x(2,j)]);
y(M,j)=nanmedian([x(M,j);x(M,j+1);x(M,j-1);x(M-1,j)]);

y(i,1)=[nanmedian([x(i,1)';x(i+1,1)';x(i-1,1)';x(i,2)'])]';
y(i,N)=[nanmedian([x(i,N)';x(i+1,N)';x(i-1,N)';x(i,N-1)'])]';

%%%%% do the middle

for k=i

y(k,j)=nanmedian([x(k,j);x(k,j+1);x(k,j-1);x(k-1,j);x(k+1,j)]);

end


