0

I have the following code structure:

result_matrix = np.zeros((n,n))
for i in range(data1.shape[0]):
    for j in range(data1.shape[1]):
        result_matrix[i,j] = myfct(data1[i,:], data2[:,j])

Can we solve this with a more numpy-y way - possibly with ufunc?

Make42
  • 12,236
  • 24
  • 79
  • 155
  • Depends on - `myfct`. – Divakar Apr 03 '19 at 17:51
  • @Divakar: actually the point is to define your own "product" arbitrarily, not to find a solution to some edge cases. – Make42 Apr 03 '19 at 19:41
  • All ufuncs support broadcasting so if your ufunc takes two arguments you can do `ufunc(x[:,None],y)`. https://docs.scipy.org/doc/numpy/reference/ufuncs.html – overfull hbox Apr 03 '19 at 20:11
  • 1
    So `myfct` is an arbitrary function that takes two 1d arrays as input, and returns a scalar? There are ways of wrapping it to hide the python level iteration, but no code to turn it into a fast compiled function. For that you have to look outside of `numpy`. – hpaulj Apr 03 '19 at 20:18
  • @tch: ufuncs seem to work on the elements, not on the rows of data1 and data2. I don't see how to change that behavior. If you know how to do it after all, please show a specific example. – Make42 Apr 03 '19 at 20:44
  • @Make42, yes,the ufuncs act on scalars, however if you apply them to an array then they follow the broadcasting rules (see the broadcasting section in my first comment). Thus, if `myfct` is a ufunc, you can use broadcasting to take advantage of the complied function and avoid a python loop. You can create custom ufuncs using `frompyfunc`, but like @hpaulj notes, it won't turn it into a complied function. – overfull hbox Apr 03 '19 at 21:44
  • `frompyfunc` uses broadcasting rules to pass scalar elements to the function. `vectorize` has a `signature` that lets you pass 1d (or other) arrays to the function, but it's even slower. https://stackoverflow.com/questions/55330169/numpy-vectorize-of-function-that-returns-an-array – hpaulj Apr 03 '19 at 22:01

0 Answers0