M-V
M-V

Reputation: 5237

How do I vectorize this expression with Python numpy?

Given numpy arrays P(N), D(N, N), I want to compute array A(N):

A_i = SUM(P_i - P_j) where j is such that D[i][j] is True
A_i = 0 otherwise

So,

A_i = N*P_i - (P_m + P_n+...) where D[i][m], D[i][n],... are all True

I could write the above using a double loop and enumerate(), but it is quite slow. Just wondering how I can write this in terms of numpy ufuncs.

Upvotes: 4

Views: 103

Answers (1)

IanH
IanH

Reputation: 10690

If I've understood the question right, here's one way to do it.

A = P*D.sum(axis=1)-D.dot(P)

Upvotes: 6

Related Questions