Find neighboring nodes in a list of node positions
3 ビュー (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
採用された回答
Image Analyst
2018 年 3 月 9 日
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
0 件のコメント
その他の回答 (1 件)
David Fletcher
2018 年 3 月 8 日
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
0 件のコメント
参考
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!