问题
I have a region with about 144 points. What i want to achieve is to measure the distance of a point with all others and store it in an array. I want to do this for all the points. If possible i would like to store this data in such a manner that there in no repetition. And i should be able to make queries like- All the distances between all the points without repetition, sum of all the distances for point no56 etc.
I have a 3*144 array with two columns storing the coordinates of the points.
回答1:
A possible solution (I am not really clear with what you mean by no repetition, though):
X are your points with coordinates x = X(:,1), y = X(:,2)
dist = sqrt(bsxfun(@minus,X(:,1),X(:,1)').^2 + bsxfun(@minus,X(:,2),X(:,2)').^2)
so
dist(i,j) is the euclidean distance between i and j
of course the matrix is symmetric. You can easily reduce the complexity involved.
回答2:
Let's say your array is A
, where each column stores the coordinates of a single point. To obtain the combinations of all point pairs (without repetitions), use nchoosek:
pairs = nchoosek(1:size(A, 2), 2)
Then calculate the Euclidean distance like so:
dist = sqrt(sum((A(:, pairs(:, 1)) - A(:, pairs(:, 2))) .^ 2, 1))
If you have the Statistics Toolbox installed, you can use pdist(A) instead for the same effect.
回答3:
If you have the statistics toolbox, and if you have all your data in the array X, then
D = pdist(X)
gives all the pairwise distances between all points in X.
来源:https://stackoverflow.com/questions/14483468/calculating-distance-of-all-the-points-in-a-region-with-each-other