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

Question:

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])
Asked By: I'mahdi

||

Answers:

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])

Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.