Euclidean distance between two vectors (single row matrix)

user648129 picture user648129 · Nov 13, 2012 · Viewed 42.9k times · Source

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.

Answer

kol picture kol · Nov 13, 2012
diff = A - B;
distance = sqrt(diff * diff');

or

distance = norm(A - B);