Smallest distance between matrix and vector

I have an NxM matrix and one vector with length M. I need the smallest distance from all distances between each row of the matrix and a single vector.

My approach was to create a second matrix using repmat and calculate the distances between each row, but I only get the total distance:

matrix2 = repmat(vector, N, 1);
norm(matrix1 - matrix2, 2)

      

+3


source to share


2 answers


Let me show you this with an example:

m = rand (5, 2);  # Your matrix with reference points
v = rand (1, 2);  # Your vector

tmp = bsxfun(@minus, m, v);
d = hypot (tmp(:,1), tmp(:,2)); # Difference between v and all rows in m

# Find samllest distance
[dmin, ix] = min (d)

# visualize it
scatter (m(:,1), m(:,2), 8, "red");
hold on
plot([v(1), m(ix, 1)], [v(2), m(ix, 2)], "-*")
hold off

print ("out.png")

      



The red bubbles are points at m (2D case) and "*" is v. The blue line connects v to one of the m closest to.

Smallest distance

+1


source


I think that on octave

you can use automatic broadcasting

to get distances without repmat-ing

or using norm

like this -

dist = sum((matrix1 - vector).^2,2)

      




As MATLAB

you can avoid repmat

using bsxfun

, as -

dist = sum(bsxfun(@minus,matrix1,vector).^2,2)

      




And, if you still want to continue with repmat

, you can get the distances like this:

matrix2 = repmat(vector, N, 1);
dist = sum((matrix1 - matrix2).^2,2)

      




Finally, to get the smallest distance and corresponding row index, you can use min

-

[smallest_dist,minrow_ind] = min(dist)

      

+1


source







All Articles