title: Numpy broadcasting elementwise product on all pairs of rows?
body: <p>I have a 1d ndarray <code>A</code> of shape (n,) and a 2d ndarray <code>E</code> of shape (n,m). I am trying to preform the following calculation (the circle-dot denotes element wise multiplication):</p>
  
  <p><a href="https://i.stack.imgur.com/biyUY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/biyUY.png" alt="enter image description here"></a></p>
  
  <p>I have written it using with a for loop, but this block of code is called thousands of times, and I was hoping there was a way to accomplish this with broadcasting or numpy functions. The following is my for loop solution I'm trying to rewrite:</p>
  
  <pre><code>def fun(E, A):
      X = E * A[:,np.newaxis]
      R = np.zeros(E.shape[-1])
      for ii in xrange(len(E)-1):
          for jj in xrange(ii+1, len(E)):
              R += X[ii] * X[jj]
      return R
  </code></pre>
  
  <p>Any help would be appreciated.</p>
  
  <p>Current approach, but still not working:</p>
  
  <pre><code>def fun1(E, A):
      X = E * A[:,np.newaxis]
      R = np.zeros(E.shape[-1])
      for ii in xrange(len(E)-1):
          for jj in xrange(ii+1, len(E)):
              R += X[ii] * X[jj]
      return R
  
  def fun2(E, A):
      n = E.shape[0]
      m = E.shape[1]
  
      A_ = np.triu(A[1:] * A[:-1].reshape(-1,1))
      E_ = E[1:] * E[:-1] 
      R = np.sum((A_.reshape(n-1, 1, n-1) * E_.T).transpose(0,2,1).reshape(n-1*n-1,m), axis=0)
  
      return R
  
  A = np.arange(4,9)
  E = np.arange(20).reshape((5,4))
  
  print fun1(E,A)
  print fun2(E,A)
  </code></pre>