Calculation of the Euclidean distance of pairs of three-dimensional points in matlaba

I have an Nx3 array containing N 3D points

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

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

+3
source share
3 answers

The problem with your problem is to make an N * N matrix, and the result should return in that matrix without using loops. I overcome this problem by providing a suitable size for the Bsxfun function. By default, X and ReshapedX must be the same size when calling the bsxfun function. But if the size of the matrices is not equal, and one of them has a singleton (equal to 1) dimension, the matrix is ​​actually replicated along this dimension in accordance with the other matrix. Therefore, it returns the matrix N * 3 * N, which provides the subtraction of each three-dimensional point from the others.

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

Use pdist and squareform :

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

For beginners, it can be a good exercise to calculate the distance matrix D using (hover over this solution).

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

+1
source

To complete the Divakar comment:

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

All Articles