Euclidean distance between two vectors (single row matrix)

情到浓时终转凉″ 提交于 2019-12-03 11:58:55

问题


I have two vectors (single row matrices). Assume that we already know the length len.

A = [ x1 x2 x3 x4 x5 .... ]
B = [ y1 y2 y3 y4 y5 .... ]

To calculate Euclidean distance between them what is the fastest method. My first attempt is:

diff = A - B
sum = 0
for column = 1:len
    sum += diff(1, column)^2
distance = sqrt(sum)

I have loop through this methods millions of times. So, I am looking for something which is fast and correct. Note that I am not using MATLAB and don't have pdist2 API available.


回答1:


diff = A - B;
distance = sqrt(diff * diff');

or

distance = norm(A - B);



回答2:


[val idx]    =  sort(sum(abs(Ti-Qi)./(1+Ti+Qi)));   

or

[val idx]    =  sort(sqrt(sum((Ti-Qi).^2))); 

Val is the value and idx is the original index value of the column being sorted after applying Euclidean distance. (Matlab Code)




回答3:


To add to @kol answer,

diff = A - B;
distance = sqrt(sum(diff * diff')) % sum of squared diff

or

distance = norm(A-B);


来源:https://stackoverflow.com/questions/13368597/euclidean-distance-between-two-vectors-single-row-matrix

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