Find neighboring nodes in a list of node positions

2 views (last 30 days)
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?

Accepted Answer

Image Analyst
Image Analyst on 9 Mar 2018
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

More Answers (1)

David Fletcher
David Fletcher on 8 Mar 2018
Something like this:
x = randn(10,1);
y = randn(10,1);
%set desired distance
maxDistance=1.6;
%set node of interest
node=4;
pos=[x y];
nodeCoords=pos(node,:);
%Calculate distance from specified node (euclidean)
distFromNode=sqrt((pos(:,1)-nodeCoords(1,1)).^2+(pos(:,2)-nodeCoords(1,2)).^2);
%Create index to points within specified maxDistance
ind=distFromNode<=maxDistance;
%List of node indexes within specified distance
indexes=1:length(x);
isWithin_Index=indexes(ind)
%List of node coords within specified distance
isWithin_Position=pos(ind,:)
Though you may want to modify it so that the node doesn't report that it is within maxDistance of itself

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!