title: Matrix of "for x in vectors: for y in vectors:", without two for loops
body: <p>Can one get the cartesian outer product of two set of vectors without using two for loops? It is slow because the data is large.</p>
  <pre><code>[[f(x,y) for x in vectors] for y in vectors]
  </code></pre>
  <p>I am trying to do an agglomerative clustering project in python and for this, I need to create a distance matrix.
  This is the code that I have to define the function for the distance matrix:</p>
  <pre><code> def distance_matrix(vectors):
      s = np.zeros((len(vectors), len(vectors)))
      for i in range(len(vectors)):
          for v in range(len(vectors)):
              s[i, v] = dissimilarity(vectors[i], vectors[v])
      return s 
  </code></pre>
  <p>What it should do is take a take a list of NumPy arrays and return a 2D NumPy array d where the entry d[i,j] should contain the dissimilarity between vectors[i] and vectors[j].</p>
  <p>In this case, vectors is the list of NumPy arrays and the dissimilarity is calculated by:</p>
  <pre><code>def dissimilarity(v1, v2):
      return (1-(v1.dot(v2)/(np.linalg.norm(v1)*np.linalg.norm(v2))))
  </code></pre>
  <p>or in other words, the dissimilarity is the cosine dissimilarity between two 1D NumPy arrays.</p>
  <p>My goal is to find a way to get the distance matrix without the double for loops but still have the computational time be very small.</p>