Search code examples
numpyvectorization

Vectorized implementation of np array difference


Let's assume I have two arrays: x = [1,2,3] and y = [ 0,1,2]. x and y arrays always have the same length. What I want to do is x - y_i for i in len(y). The vanilla implementation of the above calculation is as follows:

diff = np.zeros((x.shape[0]))
for i in range(y.shape[0]):
  diff[i] = np.sum(x - y[i])

My question is about vectorized implementation of the above code. Is there any way to implement the above calculation without using a loop?

thanks in advance.


Solution

  • A possible solution, using numpy broadcasting:

    np.sum(x - y[:, None], axis=1)
    

    Output:

    array([6, 3, 0])