title: Vectorized matrix manhattan distance in numpy
body: <p>I'm trying to implement an efficient vectorized <code>numpy</code> to make a Manhattan distance matrix. I'm familiar with the construct used to create an efficient Euclidean distance matrix using dot products as follows:</p>
  
  <pre><code>A = [[1, 2]   
       [2, 1]]
  
  B = [[1, 1],
       [2, 2],
       [1, 3],
       [1, 4]]
  
  def euclidean_distmtx(X, X):
      f = -2 * np.dot(X, Y.T)
      xsq = np.power(X, 2).sum(axis=1).reshape((-1, 1))
      ysq = np.power(Y, 2).sum(axis=1)
      return np.sqrt(xsq + f + ysq)
  </code></pre>
  
  <p>I want to implement somthing similar but using Manhattan distance instead. So far I've got close but fell short trying to rearrange the absolute differences. As I understand it, the Manhattan distance is</p>
  
  <p><img src="https://latex.codecogs.com/gif.latex?%5Csum_i&space;|x_i&space;-&space;y_i|&space;=&space;|x_1&space;-&space;y_1|&space;&plus;&space;|x_2&space;-&space;y_2|&space;&plus;&space;..." alt="\sum_i |x_i - y_i| = |x_1 - y_1| + |x_2 - y_2| + ..."></p>
  
  <p>I tried to solve this by considering if the absolute function didn't apply at all giving me this equivalence</p>
  
  <p><img src="https://latex.codecogs.com/gif.latex?%5Csum_i&space;x_i&space;-&space;y_i&space;=&space;%5Csum_i&space;x_i&space;-&space;%5Csum_i&space;y_i" alt="\sum_i x_i - y_i = \sum_i x_i - \sum_i y_i"></p>
  
  <p>which gives me the following vectorization</p>
  
  <pre><code>def manhattan_distmtx(X, Y):
      f = np.dot(X.sum(axis=1).reshape(-1, 1), Y.sum(axis=1).reshape(-1, 1).T)
      return f / Y.sum(axis=1) - Y.sum(axis=1)
  </code></pre>
  
  <p>I think I'm the right track but I just can't move the values around without removing that absolute function around the difference between each vector elements. I'm sure there's a clever trick around the absolute values, possibly by using <code>np.sqrt</code> of a squared value or something but I can't seem to realize it.</p>