2

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?

1 Answer 1

4

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()
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks but this definitely not equivalent to np.sum(X[:, np.newaxis] * y, axis=1) . I want a 1d array like [sum(X[1]*y), sum(X[2]*y), sum(X[3]*y)] and so on.
Ah. In that case, does X * y.sum() return what you want?
ah damn it. it does. this was a really dumb question.
No worries - I've often spent ages trying to figure out something that had a simple solution in the end
@Manoj - the answer should be up to date now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.