could anyone help me to calculate the euclidean distance for the matrix.
1 次查看(过去 30 天)
显示 更早的评论
A= [1.8667 0.1553;
-0.0844 2.4322;
-0.3485 1.4434;
2.3628 0.6821]
I want to calculate the euclidean distance of first row with respect to second,third and fourth row.
Similarly i want to calculate the euclidean distance of second row with respect to first,third and fourth row and so on.
could anyone please help me onthis.
0 个评论
采纳的回答
更多回答(5 个)
Christine Tobler
2019-9-11
For MATLAB R2017b or later, you can use the vecnorm function for a simpler construction than the one involving sqrt, sum, and .^2:
vecnorm(permute(A,[1,3,2]) - permute(A,[3,1,2]), 2, 3)
This will give the exact same result as constructing two for-loops and computing B(i, j) = norm(x(i, :) - x(j, :)) individually for each combination.
0 个评论
Bruno Luong
2019-9-25
Hi Christtine, very good initiative. I think at least 90% of use-case would be p=2.
0 个评论
Fabio Freschi
2019-9-11
编辑:Fabio Freschi
2019-9-11
I have found that this is usually the fastest way, since the square of the binomial is unrolled
D = sqrt(abs(bsxfun(@plus,sum(A.*A,2),sum(A.*A,2).')-2*A*A'));
If you have two sets of points A and B
D = sqrt(abs(bsxfun(@plus,sum(A.*A,2),sum(B.*B,2).')-2*A*B'));
3 个评论
Bruno Luong
2019-9-11
编辑:Bruno Luong
2019-9-11
The decompose method might have worst roundoff numerical issue:
A=[1e9 0;
1e9+1 0]
D = sqrt(abs(bsxfun(@plus,sum(A.*A,2),sum(A.*A,2).')-2*A*A'))
B = sqrt(sum(bsxfun(@minus,permute(A,[1,3,2]),permute(A,[3,1,2])).^2,3))
B is correct D is not.
It could even return complex numbers.
Fabio Freschi
2019-9-11
Good point @Bruno Luong
I used this function in a "safe" environment and never met this condition. In any case, thanks for pointing out
Bruno Luong
2019-9-11
I would put as comment of Christine's vecnorm soluton, but somehow Answers rejects it.
The vecnorm is slower than standard solution (Stephen's) in case of p = 2.
N = 10000;
A = rand(N,2);
tic
B = sqrt(sum((permute(A,[1,3,2])-permute(A,[3,1,2])).^2,3));
toc % Elapsed time is 1.249531 seconds.
tic
C = vecnorm(permute(A,[1,3,2]) - permute(A,[3,1,2]), 2, 3);
toc % Elapsed time is 4.590562 seconds.
0 个评论
Christine Tobler
2019-9-24
编辑:Christine Tobler
2019-9-24
Hi Bruno, I have the same problem where I can't comment on your answer, so adding another answer here.
That's a good point - vecnorm returns the exact same value as vecnorm, however it's not been optimized for performance as sum. Still, with all the additional overhead in the computation using sum, .^2 and sqrt, it would make sense for vecnorm to be faster here. I've made an enhancement request for this.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!