Neglecting edge conditions this is a simple case of subscript indexing:
r = 3;
c = 3;
n = 4;
M = magic(10);
sub = M((r-n):(r+n), (c-n):(c+n))
where r
is your target points row number, c
is it's columns number and n
is the neighbourhood size. This will work expect for edge cases but we can handle that like this:
sub = M(max((r-n), 1):min((r+n), end), max((c-n),1):min((c+n),end))
if instead of starting at row r-n
, which could be less than 1
, rather start at the larger of either r-n
or 1
. Then to stop going past the end just choose the smaller of either r+n
or end
.