Are there any known algorithms for identifying the coordinates of the nearest neighbours of a 2D square lattice?
13 次查看(过去 30 天)
显示 更早的评论
I'm looking for a code that takes these inputs: (i) 2D lattice in x,y coordinates (ii) coordinate of interest (iii) integer n, and outputs the coordinates of the n-th nearest neighbours.
For example:
- Input (i) some arbitrary lattice (ii) (0,0) as coordinate of interest (iii) 2 - for next nearest neighbours.
- Output (-1,0), (0,1), (1,0), (0,-1) for nearest neighbours, (-1,1), (1,1), (1,-1), (-1,-1) for next nearest neighbours.
If there is no code around, I will write one up.
Thanks a bunch!
0 个评论
采纳的回答
Guillaume
2018-1-12
Assuming the lattice is not too huge, can't you just calculate the distance from your point to every lattice point, sort the distances and pick the nth first points (watching out for equality)? E.g.:
lattice = [];
[lattice(:, :, 1), lattice(:, :, 2)] = ndgrid(-10:10);
lattice = reshape(lattice, [], 2) %demo lattice as Nx2 matrix, each row is a lattice point
querypoint = [0 0]
neighbours = 2
distances = hypot(querypoint(:, 1) - lattice(:, 1), querypoint(:, 2) - lattice(:, 2));
[d, ~, order] = unique(distances); %sort the distance and get unique id for each distance
rows = (1:numel(order)).';
if d(1) == 0
%point on lattice coincide with query point, remove from result
order = order - 1;
rows(order == 0) = [];
order(order == 0) = [];
end
result = accumarray(order(order <= neighbours), rows(order <= neighbours), [],@(v) {lattice(v, :)});
celldisp(result)
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Read, Write, and Modify Image 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!