How to find Moore neighbourhood in a 2D cellular automata?

18 views (last 30 days)
I am trying to find the list of neighbours inside a Moore neighbourhood of variable length in a 2D cellular automata (will run different conditions on them later on). I have attached a link of an image for a Moore neighbourhood with variable r from Wolfram MathWorld, in case anyone is interested. In an NXN grid, my code is as below. This is ok for r = 1; but for r>1, it keeps missing some values. For example, for r = 2, it misses (i-1,j-2);(i+1,j-2);(i+2,j-1);(i+2,j+1);(i+1,j+2);(i-1,j+2);(i-2,j+1);(i-2,j-1).
for i = 1:N
for j = 1:N
for r = 1:R
neighbour_ij = [(i-r,j-r);(i,j-r);(i+r,j-r); (i+r,j);(i+r,j+r);(i,j+r);(i-r,j+r);(i-r,j)];
end
end

Accepted Answer

Bee
Bee on 29 Jun 2018
Edited: Bee on 29 Jun 2018
In case someone is looking for this, I am sharing the way I solved it - there are more efficient ways to do this, which I don't know, but mine at least works :)
% Take a grid, G = NXN
% define a neighbourhood matrix
moore = cell(size(Z));
% for example, r = 1; the neighbourhood size = (2*r+1)^2
for i = 1:N
for j = 1:N
x = [i-r:i+r]; %row subscript
x(x<=0)=[]; x(x>N)=[]; %discarding values that are out of range, for absorbing boundary
%for toroidal neighbourhood, discard the previous line which is for absorbing boundary
%x(x<=0) = N+ x(x<=0);
%x(x>N) = -N+ x(x>N);
%end of toroidal neighbourhood
y = [j-r:j+r]; %column subscript
y(y<=0) = []; y(y>N) = []; % absorbing boundary, i.e. edge nodes have fewer neighbours, corner
% node has only 3 neighbours etc.
%for toroidal neighbourhood, discard the previous line which is for absorbing boundary
%x(y<=0) = N+ y(y<=0);
%x(y>N) = -N+ y(y>N);
%end of toroidal neighbourhood
for k = 1:length(x)
for l = 1:length(y)
moore{i,j} = [moore{i,j};(Z(x(k),y(l)))];
end
end
moore{i,j} = unique(moore{i,j});
end
end

More Answers (3)

KSSV
KSSV on 21 Jun 2018
Read about knnsearch
  1 Comment
Bee
Bee on 29 Jun 2018
I couldn't relate them, knnsearch finds nearest neighbours in a matrix, X comparing it with another matrix. Y - that's what I understood from reading the doc, whereas I am looking for nearest neighbour of each element in vector X.

Sign in to comment.


Mauro
Mauro on 11 Mar 2025 at 12:57
function [out] = M_neighbors(G,x,ner)
% G: input matrix
% x: index_target (position in the grid; e.g. 56)
% ner: Moore radius (r = 1,2,3 ...)
[N, ~] = size(pop);
t = zeros(1, N*N);
col = mod(x-1, N) + 1;
row = floor((x-1) / N) + 1;
neigh_cnt = 0;
for yy = -ner:ner
for xx = -ner:ner
t = mod(row+yy-1+N, N) * N + mod(col+xx-1+N, N) + 1;
if t == x
continue;
end
neigh_cnt = neigh_cnt + 1;
neigh(neigh_cnt) = t;
end
end
out = neigh;
return

Mauro
Mauro on 11 Mar 2025 at 12:59
[N, ~] = size(pop);
should be
[N, ~] = size(G);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!