Numpythonic way to perform vector substraction where the operands has different shape each other (a,n) - (b,n)

36 views Asked by At

I have two matrix operand like these:

a = np.array([[1,2], [3,4], [5,6], [7,8]])
b = np.array([[9,10], [11,12], [13,14]])

If we debug a and b, they will look like these:

[[1 2]
 [3 4]
 [5 6]
 [7 8]]
(4, 2)
int32

[[ 9 10]
 [11 12]
 [13 14]]
(3, 2)
int32

I can achieve what I want with this way, where c is result:

c = []
for i in range(b.shape[0]):
  c.append(b[i] - a)
c = np.array(c)

Now, the c will be looks like this:

[[[ 8  8]
  [ 6  6]
  [ 4  4]
  [ 2  2]]

 [[10 10]
  [ 8  8]
  [ 6  6]
  [ 4  4]]

 [[12 12]
  [10 10]
  [ 8  8]
  [ 6  6]]]
(3, 4, 2)
int32

As you see, how I perform substraction was still using for looping, is there numpythonic way where I can substract without using loop so that I can utilize numpy optimization therefore the performance will be faster since numpy is using C language.

2

There are 2 answers

2
the_sean_c On BEST ANSWER

You can do it like this:

>>> a = np.array([[1,2], [3,4], [5,6], [7,8]])
>>> b = np.array([[9,10], [11,12], [13,14]])
>>> b[:, None, :] - a[None, :, :]
    array([[[ 8,  8],
        [ 6,  6],
        [ 4,  4],
        [ 2,  2]],
    
       [[10, 10],
        [ 8,  8],
        [ 6,  6],
        [ 4,  4]],
    
       [[12, 12],
        [10, 10],
        [ 8,  8],
        [ 6,  6]]])
0
wim On

To do this directly with numpy array operators would be:

b[:, None] - a

See broadcasting in the docs.