MATLAB: Find neighboring nodes in a list of node positions

MATLABvectorization

I have two vectors of X and Y positions
x = randn(10,1);
y = randn(10,1);
So x(1) with y(1) together make the position of node 1
What I want to do is find all other nodes that are lets say in a distance of d=.3 from that node, and do this for all nodes in the list.
What is a good vectorized way of doing this without having a double for loop?

Best Answer

If you have the Statistics and Machine Learning Toolbox, you can simply use pdist2() to find distances between all possible pairs of x,y locations:
% Set up:
x = randn(10,1);
y = randn(10,1);
xy = [x, y];
% Find distances between every possible pair of points:
distances = pdist2(xy, xy)
% Find distances less than 0.3
closeDistances = distances < 0.3 & distances > 0
% Get indexes of those close distances.
[rows, columns] = find(closeDistances)
% Done! Now, for info, print out those nodes that are close
for k = 1 : length(rows)
fprintf('Node %d and %d are close, with a distance between them of %.3f.\n',...
rows(k), columns(k), distances(rows(k), columns(k)));
end
Related Question