Array operations using multiple indices of same array
<p>I am very new to Python, and I am trying to get used to performing Python's array operations rather than looping through arrays. Below is an example of the kind of looping operation I am doing, but am unable to work out a suitable pure array operation that does not rely on loops:</p>

<pre><code>import numpy as np

def f(arg1, arg2):
  # an arbitrary function


def myFunction(a1DNumpyArray):
  A = a1DNumpyArray      

  # Create a square array with each dimension the size of the argument array.
  B = np.zeros((A.size, A.size))

  # Function f is a function of two elements of the 1D array. For each 
  # element, i, I want to perform the function on it and every element 
  # before it, and store the result in the square array, multiplied by 
  # the difference between the ith and (i-1)th element.
  for i in range(A.size):
    B[i,:i] = f(A[i], A[:i])*(A[i]-A[i-1])

  # Sum through j and return full sums as 1D array.
  return np.sum(B, axis=0)
</code></pre>

<p>In short, I am integrating a function which takes two elements of the same array as arguments, returning an array of results of the integral. </p>

<p>Is there a more compact way to do this, without using loops? </p>

<p>The use of an arbitrary <code>f</code> function, and this <code>[i, :i]</code> business complicates by passing a loop.</p>

<p>Most of the fast compiled <code>numpy</code> operations work on the whole array, or whole rows and/or columns, and effectively do so in parallel.  Loops that are inherently sequential (value from one loop depends on the previous) don't fit well.  And different size lists or arrays in each loop are also a good indicator that 'vectorizing' will be difficult.</p>

<pre><code>for i in range(A.size):
    B[i,:i] = f(A[i], A[:i])*(A[i]-A[i-1])
</code></pre>

<p>With a sample <code>A</code> and known <code>f</code> (as simple as <code>arg1*arg2</code>), I'd generate a <code>B</code> array, and look for patterns that treat <code>B</code> as a whole.  At first glance it looks like your <code>B</code> is a lower triangle.  There are functions to help index those.  But that final sum might change the picture.</p>

<p>Sometimes I tackle these problems with a bottom up approach, trying to remove inner loops first.  But in this case, I think some sort of big-picture approach is needed.</p>

python arrays numpy