简体   繁体   中英

broadcasting element-wise operation in numpy

I have two vectors x and y . x has a size of 900 and y has a size of 12. I want to take each element in x and subtract it from all elements in y and then take the argmin . The resulted vector has a size of 900 and each element's value is between 0 and 11. Here is a for loop which I am trying to avoid:

result = []
for x_e in x:
   result.append(np.argmin(np.abs(y - x_e)))

You can broadcast a column array onto a rows. So you can just add an axis, subtract, and pass this to argmin

import numpy as np

x = np.array([4, 5, 7, 12, 9, 3, 99, 23, 57, 65])
y = np.array([100, 200, -50])

np.argmin(y - x[:, None], axis=1 )
# array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

This is the same result you get with your loop.

Use np.repeat to repeat x 12 times (the size of y). Then you can use the transpose of X (now a matrix or 2d-array) to do the substraction. Here is an example with some sample data:

x = np.array([[2,3,4]])
y = np.array([2, 1])
x = np.repeat(x, y.shape[0], axis=0)
x.T - y

And then you can take the element-wise argmin of the resulting array.

something like that may work:

import numpy as np

X=np.random.rand(900,1)
Y=np.random.random((1,12))*10
X_temp=np.repeat(X, Y.shape[-1],axis=1)

sub_esult=X_temp-Y

final_result=np.argmin(sub_esult, axis=1)

print(final_result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM