Home > OS >  can vectorize this for-loop with update variable in each iterate?
can vectorize this for-loop with update variable in each iterate?

Time:10-15

Can we vectorize this for-loop that finally result update in each iterate and using the result in for like below:

x = np.array([[1,2],[2,3],[3,4]])
y = np.array([1,-1,1])
z = np.array([-1,1,-1])

w = 2
out = np.array([10,20])
for xi,yi,zi in zip(x, y, z):
    out = out   (w*(yi-zi))*xi

Output:

>>> out
array([ 18, 32])

CodePudding user response:

You could simply use:

(w*(y-z)*x.T).sum(1)

output: array([ 8, 12])

Add existing array:

out = np.array([10,20])
out  = (w*(y-z)*x.T).sum(1)

output: array([18, 32])

  • Related