Suppose I have two matrices Nx2, Mx2 representing N, M 2d vectors respectively. Is there a simple and good way to calculate distances between each vector pair (n, m)?
The easy but inefficient way is of course:
d = zeros(N, M);
for i = 1:N,
for j = 1:M,
d(i,j) = norm(n(i,:) - m(j,:));
endfor;
endfor;
The closest answer I've found is bsxfun, used like so:
bsxfun(inline("x-y"),[1,2,3,4],[3;4;5;6])
ans =
-2 -1 0 1
-3 -2 -1 0
-4 -3 -2 -1
-5 -4 -3 -2
In Python this would look like: distance_matrix = (n[:,:,nexaxis] * m[:,newaxis,:]); distance_matrix = distance_matrix**2; distance_matrix = sqrt(distance_matrix.sum(axis=1));
If you only need to know the closest n-vectors there are much better ways to do this!
– meawoppl Feb 27 '12 at 20:46cartprod, so now I can write: (1)x = cartprod(n(:,1), m(:,1));(2)y = cartprod(n(:,2), m(:,2));(3)d = sqrt((x(:,1)-x(:,2)).^2+(y(:,1)-y(:,2)).^2)..which runs much faster! – Kelley van Evert Feb 27 '12 at 23:36