-
Notifications
You must be signed in to change notification settings - Fork 0
/
nearest_neighbors_2D_open.m
47 lines (44 loc) · 1.69 KB
/
nearest_neighbors_2D_open.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function [val, pos] = nearest_neighbors_2D_open(G, i, j)
% Takes a matrix 'G' and position indices 'i', 'j'. Returns a values-vector
% 'val' and a positions-matrix 'pos' (a column per element: [row; column])
% of nearest neighboring elements to G(i,j).
%%% NOTE: Considers "open" boundaries: G(L+1,L+1) := G(1,1).
L = size(G, 1);
if i ~= 1
if i ~= L
if j ~= 1
if j ~= L % Inner element
val = [G(i-1,j), G(i+1,j), G(i,j-1), G(i,j+1)];
pos = [i-1, i+1, i, i; j, j, j-1, j+1];
else % Inner right side
val = [G(i-1,j), G(i+1,j), G(i,j-1), G(i,1)];
pos = [i-1, i+1, i, i; j, j, j-1, 1];
end
else % Inner left side
val = [G(i-1,j), G(i+1,j), G(i,L), G(i,j+1)];
pos = [i-1, i+1, i, i; j, j, L, j+1];
end
elseif j ~= 1
if j ~= L % Inner bottom
val = [G(i-1,j), G(1,j), G(i,j-1), G(i,j+1)];
pos = [i-1, 1, i, i; j, j, j-1, j+1];
else % Bottom-right corner
val = [G(i-1,j), G(1,j), G(i,j-1), G(i,1)];
pos = [i-1, 1, i, i; j, j, j-1, 1];
end
else % Bottom-left corner
val = [G(i-1,j), G(1,j), G(i,L), G(i,j+1)];
pos = [i-1, 1, i, i; j, j, L, j+1];
end
elseif j ~= 1
if j ~= L % Inner top
val = [G(L,j), G(i+1,j), G(i,j-1), G(i,j+1)];
pos = [L, i+1, i, i; j, j, j-1, j+1];
else % Top-right corner
val = [G(L,j), G(i+1,j), G(i,j-1), G(i,1)];
pos = [L, i+1, i, i; j, j, j-1, 1];
end
else % Top-left corner
val = [G(L,j), G(i+1,j), G(i,L), G(i,j+1)];
pos = [L, i+1, i, i; j, j, L, j+1];
end