1

Let's say I have a N × 1 × 1 array a, and N × M × M array b as NumPy arrays. I want to do the elementwise multiplication:

c[i,:,:] = a[i]*b[i,:,:]

without iterating over i. The function np.multiply(a,b) seems to do the job. However, I do not quite understand the inner workings of this function when a and b do not have the same size. I know that when it has the same size then it just multiplies elementwise. I assume when they are not of the same size then it does some broadcasting to change the dimensions of one of the arrays but how?

Matt Hall
  • 7,614
  • 1
  • 23
  • 36
Sina
  • 401
  • 5
  • 12
  • 1
    Broadcasting is not straightforward at first but it will make your code much faster. Just read the [official doc](https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html) a few times and then practice. You do not need to use `multiply`, `c=a*b` will also work. – Brenlla May 14 '18 at 16:48
  • Have a read of this question too: https://stackoverflow.com/questions/11178179/numpy-array-broadcasting-rules?rq=1 – Matt Hall May 15 '18 at 11:33

0 Answers0