Reputation: 971
I have two numpy arrays, X and y. X is of size m, and y is of size n. I need to multiply each element of y by every element of X, and then sum up.
Something like [sum(X[0]*y) sum(X[1]*y) sum(X[n]*y)]
This is what I mean
np.sum(X[:, np.newaxis] * y, axis=1)
However typically X and y are really large and so doing
X[:, np.newaxis] * y
creates a huge temporary array, which blows up stuff. Is there a better way of implementing this?
Upvotes: 2
Views: 2298
Reputation: 176750
If you're multiplying each element of y
by every element of X
, just multiply all the elements of X
together first, then use multiply the array y
by this number and sum:
num = X.prod()
(num * y).sum()
Edit: the array you specify can be obtained by multiplying the array X
by the sum of the elements of y
:
X * y.sum()
Upvotes: 4