title: Minimum Euclidean distance between points in two different Numpy arrays, not within
body: <p>I have two arrays of <em>x</em>-<em>y</em> coordinates, and I would like to find the minimum Euclidean distance between <em>each</em> point in one array with <em>all</em> the points in the other array. The arrays are not necessarily the same size. For example:</p>
  
  <pre><code>xy1=numpy.array(
  [[  243,  3173],
  [  525,  2997]])
  
  xy2=numpy.array(
  [[ 682, 2644],
  [ 277, 2651],
  [ 396, 2640]])
  </code></pre>
  
  <p>My current method loops through each coordinate <code>xy</code> in <code>xy1</code> and calculates the distances between that coordinate and the other coordinates.</p>
  
  <pre><code>mindist=numpy.zeros(len(xy1))
  minid=numpy.zeros(len(xy1))
  
  for i,xy in enumerate(xy1):
      dists=numpy.sqrt(numpy.sum((xy-xy2)**2,axis=1))
      mindist[i],minid[i]=dists.min(),dists.argmin()
  </code></pre>
  
  <p>Is there a way to eliminate the for loop and somehow do element-by-element calculations between the two arrays? I envision generating a distance matrix for which I could find the minimum element in each row or column.</p>
  
  <p>Another way to look at the problem. Say I concatenate <code>xy1</code> (length <em>m</em>) and <code>xy2</code> (length <em>p</em>) into <code>xy</code> (length <em>n</em>), and I store the lengths of the original arrays. Theoretically, I should then be able to generate a <em>n x n</em> distance matrix from those coordinates from which I can grab an <em>m x p</em> submatrix. Is there a way to efficiently generate this submatrix?</p>