Calculating Euclidean distance of pairs of 3D points in matlab

时间秒杀一切 提交于 2019-12-01 21:08:06

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);

Use pdist and squareform:

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

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

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

zinjaai

To complete the comment of Divakar:

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