Home > Blockchain >  How to vectorize this operation in numpy?
How to vectorize this operation in numpy?

Time:11-20

I have a 2d array s and I want to calculate differences elementwise, i.e.:

enter image description here

Since it cannot be written as a single matrix multiplication, I was wondering what is the proper way to vectorize it?

CodePudding user response:

You can use broadcasting for that: d = s[:, None, :] - s[None, :, :]. Note the None enable you to create a new dimension. Numpy implicitly perform the broadcasting operation between the two arrays.

  • Related