title: How to vectorize this python code?
body: <p>I am trying to use NumPy and vectorization operations to make a section of code run faster. I appear to have a misunderstanding of how to vectorize this code, however (probably due to an incomplete understanding of vectorization).</p>
  
  <p>Here's the working code with loops (A and B are 2D arrays of a set size, already initialized):</p>
  
  <pre><code>for k in range(num_v):
      B[:] = A[:]
      for i in range(num_v):
          for j in range(num_v):
              A[i][j] = min(B[i][j], B[i][k] + B[k][j])
  return A
  </code></pre>
  
  <p>And here is my attempt at vectorizing the above code:</p>
  
  <pre><code>for k in range(num_v):
      B = numpy.copy(A)
      A = numpy.minimum(B, B[:,k] + B[k,:])
  return A
  </code></pre>
  
  <p>For testing these, I used the following, with the code above wrapped in a function called 'algorithm':</p>
  
  <pre><code>def setup_array(edges, num_v):
      r = range(1, num_v + 1)
      A = [[None for x in r] for y in r]  # or (numpy.ones((num_v, num_v)) * 1e10) for numpy
      for i in r:
          for j in r:
              val = 1e10
              if i == j:
                  val = 0 
              elif (i,j) in edges:
                  val = edges[(i,j)]
              A[i-1][j-1] = val 
      return A
  
  A = setup_array({(1, 2): 2, (6, 4): 1, (3, 2): -3, (1, 3): 5, (3, 6): 5, (4, 5): 2, (3, 1): 4, (4, 3): 8, (3, 4): 6, (2, 4): -4, (6, 5): -5}, 6) 
  B = []
  algorithm(A, B, 6)
  </code></pre>
  
  <p>The expected outcome, and what I get with the first code is:</p>
  
  <pre><code>[[0, 2, 5, -2, 0, 10] 
   [8, 0, 4, -4, -2, 9]
   [4, -3, 0, -7, -5, 5]
   [12, 5, 8, 0, 2, 13]
   [10000000000.0, 9999999997.0, 10000000000.0, 9999999993.0, 0, 10000000000.0]
   [13, 6, 9, 1, -5, 0]]
  </code></pre>
  
  <p>The second (vectorized) function instead returns:</p>
  
  <pre><code>[[ 0. -4.  0.  0.  0.  0.]
   [ 0. -4.  0. -4.  0.  0.]
   [ 0. -4.  0.  0.  0.  0.]
   [ 0. -4.  0.  0.  0.  0.]
   [ 0. -4.  0.  0.  0.  0.]
   [ 0. -4.  0.  0. -5.  0.]]
  </code></pre>
  
  <p>What am I missing?</p>