Summation within iteration over two variables with matrix operations

Viewed 50

I have the following matrices: Q, P, q and y with shapes (100,100), (100,100), (100,100) and (100,2) respectively.

For every i, I want to compute the following: enter image description here

This is what I've tried so far, it appears to work but I know this is bad practice and painfully slow.

grad = np.zeros(100, 2)
for i in range(100):
    tmp = 0
    for j in range(100):
         tmp += ((P[i, j] - Q[i, j]) * q[i, j] * (y[i, :] - y[j, :]))
    grad[i, :] = tmp * 4

My question is how can I compute this using matrix operations instead of nested loops?

1 Answers

From your notation, try broadcasting:

grad = 4 * (((P-Q)*q)[...,None]*(y[:,None,:]-y[None])).sum(axis=1)
Related