0

Let h be a function which applies entrywise (e.g squaring, etc.). Let u and v be a 1d arrays of length k and A be a 2d array of shape n x m. Here l, n, and m can be very large!

Question. In numpy, what is an efficient way to compute the n x m array defined by B := v[0] * h(u[0] * A) + ... + v[k-1] * h(u[k-1] * A) ?

Observations

  • Of course, a naive solution is to just loop over the u[j]'s and v[j]'s and accumulate v[j] * h(u[j] * A).
  • Another solution which seems horrible (at least memory-wise is): B = np.sum(v[:, None, None] * h(u[:, None, None] * A), axis=0)
eroot163pi
  • 1,791
  • 1
  • 11
  • 23
dohmatob
  • 289
  • 4
  • 14
  • 4
    That horrible solution is the normal numpy approach. – hpaulj Sep 23 '21 at 07:24
  • 1
    You can get best of both, i.e. memory wise(for loops) and time wise(vectorize) if you add a function with numba jit https://stackoverflow.com/questions/68591676/why-np-hypot-and-np-subtract-outer-very-fast-compared-to-vanilla-broadcast-usi – eroot163pi Sep 23 '21 at 10:41
  • 1
    @eroot163pi I'd like a solution which only uses native numpy (no numba, cython, etc.). – dohmatob Sep 23 '21 at 10:50

0 Answers0