Here's my interpretation of your problem:
Given some periodic matrix A
:
>> A = magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
and some element x
(example 1
), then find the (i,j) indices of the 4 neighbours of x
. In this case, the indices (3, 4), (4,3), (4, 1), (1, 4) correspond to 12, 15, 4, 13.
Since I don't know your use case, I don't know in what format the indices are most convenient for you. But as an example, we can write a function neighbors
which returns a struct with the 4 indices of the element x
.
function out = neighbors(A, x)
[m, n] = size(A);
[i, j] = find(A == x);
mod2 = @(x) mod(x-1, [m, n])+1;
out.down = mod2([i+1, j ]);
out.up = mod2([i-1, j ]);
out.right = mod2([i , j+1]);
out.left = mod2([i , j-1]);
end
We can then run the function as follows.
A = magic(4);
out = neighbors(A, 1);
A(out.left(1), out.left(2)); % this returns 15
A(out.right(1), out.right(2)); % this returns 4
A(out.up(1), out.up(2)); % this returns 12
A(out.down(1), out.down(2)); % this returns 13
mod
. – Cris Luengo