How do I vectorize this expression with Python numpy?

numpy, python

Solution

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

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

Problem

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.

Original source