필터 지우기
필터 지우기

Ordering the closest points to a certain point

조회 수: 3 (최근 30일)
Zach
Zach 2011년 6월 27일
I have a randomly generated set of k points on a graph. I'm trying to order each points distance in reference to the other. Each point is labelled 1 to n with no particular order. I want each of the n points to create a list that has the x and y coordinates of the other points all in increasing order of distance. Here's what I tried so far but it's not working for me.
for n=1:k
x(1,n) = 50.*rand(1,1)+25;
y(1,n) = 50.*rand(1,1)+25;
end
for n=1:k;
for i=1:k;
if n~=i
d(n,i)= sqrt(((x(1,i)-x(1,n))^2)+(y(1,i)-y(1,n))^2);
else
d(n,i)=NaN
end
end
sort(d(n,:));
end
for n=1:k;
for i=1:k;
for j=1:k;
if (sqrt(((x(1,i)-x(1,n))^2)+(y(1,i)-y(1,n))^2)) == d(n,j)
x(n,j)=x(1,i);
y(n,j)=y(1,i);
end
end
end
end
So the idea is that x(n,1) would be the x coordinate of the closest point to the nth point.

채택된 답변

Walter Roberson
Walter Roberson 2011년 6월 27일
Sounds like a nearest-neighbour computation.
x = 50.*rand(1,k)+25;
y = 50.*rand(1,k)+25;
dists = cell2mat(arrayfun(@(K) bsxfun(@(J,K) hypot(x(J)-x(K),y(J)-y(K)), K, 1:k), 1:k, 'Uniform',0).');
[sorteddists, rowidx] = sort(dists,2);
This does need some enhancement, though: before doing the sort, you should remove the diagonal, as points are always distance 0 from themselves. You could sort and then remove the first column, but there is a danger in doing so: if any of the points are in exactly the same place, then because the sort is "stable", there will be a row in which the point that is in the same place sorts before the point to itself. Replacing the diagonal with -inf before doing the sort would probably work.
  댓글 수: 3
Zach
Zach 2011년 6월 27일
I see that you sorted the distances and created and index for the distances. If you could get a way to create a list so that the x and y coordinates are arranged by this distance index. So that the I can get the x and y coordinate of the closest element to another element even though that might not be the closest x and y coordinate to that element if that makes any sense.
Walter Roberson
Walter Roberson 2011년 6월 28일
Closest to [x(K) y(K)] is
J = rowidx(K,1);
[x(J) y(J)]

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by