MATLAB: Random close numbers within an array

random number generator

how can i randomly extract a number and one of its four closest 'neighbours' out of an array 100×100?

Best Answer

I would choose a random integer from 1 to 10000. We can use that as a linear index into the elements of your array, as if the array were unrolled into a vector. Since there are 100*100=10000 elements in total, this works.
Next, whatever the element is, which elements are adjacent to it? Thus up, down, right, left? For a 100x100 array, how would we find them? The trick is to understand how MATLAB stores elements in an array, and how that unrolled index works.
I'll do this for a fully general sized array, to make it more clear how things work. So assume an array of size nr by nc, thus nr rows and nc columns.
nr = 100;
nc = 100;
offset = [1 -1 nr -nr]; % down, up, right, left
% choose a random element in the matrix
randelem = randi(nr*nc,1);
% what are the neighbors of this element?
neighbor = randelem + offset;
% which of those neighors fall off the edge of the world?
[r,c] = ind2sub([nr,nc],neighbor);
neighbor((r < 1) | (c < 1) | (r > nr) | (c > nc)) = [];
% a random choice among one of those that remain
neighbor = neighbor(randi(numel(neighbor),1));
% convert back to row and column indices:
[r,c] = ind2sub([nr,nc],[randelem,neighbor]);
r
r =
55 56
c
c =
81 81