Calculating distance of all the points in a region with each other

杀马特。学长 韩版系。学妹 提交于 2019-11-27 15:14:07

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!