Here's an attempt, not the most elegant or efficient one, but still it should work.
first I assume you have the x,y coordinates of your non empty cells, something like
c=[x y];
The relative positions of the 8 nearest neighbors (n.n.) in a 2D array are given by:
nn=[1 1;1 -1;-1 1;0 -1;-1 0;0 1;1 0;-1 -1];
Let's take all possible permutation of each x,y coordinate in c
around its n.n.
permc=bsxfun(@plus,repmat(c,[1 8]),nn(:)');
Now set a vector of random n.n. out of the 8 options for each x,y coordinates:
ri=randi(8,numel(x), 1);
and use it to select random new coordinates
new_c= [ permc(sub2ind(size(permc), (1:numel(x))', 2*ri-1 )) , ...
permc(sub2ind(size(permc), (1:numel(x))', 2*ri))];
Issues:
The code doesn't check if there is a n.n. that is not free, not hard to solve having info of c
and permc
at hand.
The code doesn't care that a point is on the edge of the array, so it can select a coordinate that is either 0 or one larger than the size of the array. Again, permc
has the info to tackle this case and it can be treated separately in several ways.
That's the jist.