%contacts im=ndx(i-1,L); ip=ndx(i+1,L); jm=ndx(j-1,L); jp=ndx(j+1,L); if A(im,j)==A(i,j) %check top contact=1+contact; end if A(ip,j)==A(i,j) %check bottom contact=1+contact; end if A(i,jm)==A(i,j) %check left contact=1+contact; end if A(i,jp)==A(i,j) %check right contact=1+contact; end