Maxim
Maxim

Reputation: 231

Ramdomly replace each entry by one of its four neighbours

I iterate through a 100x100 array and pick every time four neighbours (one left of the center node, one above, one right and one below), like in the picture below

matrix with red as center node and blue as neighbours

the red one is the center node and the blue ones are the neighbours. I struggle to find a convenient way in MATLAB to pick randomly one of the neighbours.

Upvotes: 2

Views: 62

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

The following assumes that

  • Each entry is replaced by one of its original neighbours, independently of what happens to other entries.
  • Each neighbour has the same probability of being picked.
  • Neighbourhood is defined cyclically. Thus, for example, in the first column the "left" neighbour belongs to the last column.

The code builds a cyclically extended matrix for convenience, and then uses linear indexing to (randomly) select the neighbours.

x = [10 20 30 40; 50 60 70 80; 90 100 110 120]; % example data
x_ext = x([end 1:end 1], [end 1:end 1]); % cyclically extended matrix
ind = bsxfun(@plus, (2:size(x,1)+1).', (1:size(x,2))*(size(x,1)+2)); % linear indices
    % of the original matrix in the extended matrix
delta = [-1 1 -size(x_ext,1) size(x_ext,1)]; % possible displacements for neighbours,
    % as linear indices
r = delta(randi(4, size(x))); % generate random displacements
result = x_ext(ind + r); % pick neighbours in extended matrix

Example:

>> x
x =
    10    20    30    40
    50    60    70    80
    90   100   110   120
>> result
result =
    20    30    70    30
    90   100    60   120
    50   110    70    40

Upvotes: 3

Related Questions