Calculating Euclidean distance of pairs of 3D points in matlab

谁都会走 提交于 2019-12-02 01:32:07

问题


I have an Nx3 array that contains N 3D points

a1 b1 c1 
a2 b2 c2
.... 
aN bN cN 

I want to calculate Euclidean distance in a NxN array that measures the Euclidean distance between each pair of 3D points. (i,j) in result array returns the distance between (ai,bi,ci) and (aj,bj,cj). Is it possible to write a code in matlab without loop ?


回答1:


The challenge of your problem is to make a N*N matrix and the result should return in this matrix without using loops. I overcome this challenge by giving suitable dimension to Bsxfun function. By default X and ReshapedX should have the same dimensions when we call bsxfun function. But if the size of the matrixes are not equal and one of them has a singleton (equal to 1) dimension, the matrix is virtually replicated along that dimension to match the other matrix. Therefore, it returns N*3*N matrix which provides subtraction of each 3D point from the others.

ReshapedX = permute(X,[3,2,1]);
DiffX = bsxfun(@minus,X,ReshapedX);
DistX =sqrt(sum(DiffX.^2,2));
D = squeeze(DistX);



回答2:


Use pdist and squareform:

D = squareform( pdist(X, 'euclidean' ) ); 

For beginners, it can be a nice exercise to compute the distance matrix D using bsxfun (hover to see the solution).

elemDiff = bsxfun( @minus, permute(X,[ 1 3 2 ]), permute(X, [ 3 1 2 ]) );
D = sqrt( sum( elemDiff.^2, 3 ) );




回答3:


To complete the comment of Divakar:

x = rand(10,3);
pdist2(x, x, 'euclidean')   


来源:https://stackoverflow.com/questions/25780633/calculating-euclidean-distance-of-pairs-of-3d-points-in-matlab

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