nakajuice
nakajuice

Reputation: 692

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?

Upvotes: 2

Views: 34

Answers (1)

Jérôme Richard
Jérôme Richard

Reputation: 50278

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.

Upvotes: 3

Related Questions