0

I need to integrate a matrix function as in the example below:

def func(a1, a2, a3):
     return np.array([a1, (a1 + a2), a3])

The non-efficient way to do this is using three for loops. Although, I would like to make it more efficient. I thought about using "map", like:

def integral(func, a1, a2, a3, w):
    f = np.array(list(map(func, a1, a2, a3)))
    I = np.zeros((3, ))
    for fi, wi in zip(f, w):
        I = I + wi*np.array(fi)
    return I

a1, a2, a3 and w are arrays of the same size (a's are the sample points and w are the weights)

Is this the most optimized way to do so?

hpaulj
  • 221,503
  • 14
  • 230
  • 353
Gabs
  • 292
  • 5
  • 23
  • If you are going to `zip` `f` there's no point in starting with array. `zip` on a list is faster. But the `zip` loop is just `np.dot(w, f)`. – hpaulj Jan 08 '19 at 18:41

1 Answers1

1

For this function in particular you can vectorize everything.

I = w@np.vstack([a1,a1+a2,a3]).T

However, in general it isn't fast to apply a python function over a numpy array.

overfull hbox
  • 747
  • 3
  • 10
  • Ok, but that function in particular was just an example. The real function is far more complicated and has NxM dimension. – Gabs Jan 08 '19 at 17:31