Minus two arrays in python which is similar to bsxfun in matlab

Viewed 78

I have two np.arrays, say A=np.array([1,2,3]) and B=np.array([1,2,3,4]) for example. I want to compute a new array C such that the first row of C is the first element of A minus every element in B, the second row of C is the second element of A minus every element in B and the last row of C is the third element of A minus every element in B. Is it possible to code it without using any for loop or numpy repeat? I know that we can use bsxfun in matlab. I search but I cannot obtain satisfactory answer.

2 Answers

You can use numpy broadcasting by adding a new axis to A (either None or the alias np.newaxis):

C = A[:, None] - B

# array([[ 0, -1, -2, -3],
#        [ 1,  0, -1, -2],
#        [ 2,  1,  0, -1]])

Use:

c = (A - B.reshape(4, 1)).T

Output:

>>> c
array([[ 0, -1, -2, -3],
       [ 1,  0, -1, -2],
       [ 2,  1,  0, -1]])
Related