Search code examples
numpyvectorization

How to vectorize this operation in numpy?


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?


Solution

  • 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.