xxx222
xxx222

Reputation: 3254

How to improve the performance of this Python code?

Is there any way I can improve the Python code I attached below? It seems too slow for me now.

C_abs = abs(C)
_, n = C_abs.shape

G = np.zeros((n, n))
for i in xrange(n):
    for j in xrange(n):
        G[i,j] = C_abs[i,j]+C_abs[j,i]

Upvotes: 3

Views: 96

Answers (1)

Divakar
Divakar

Reputation: 221754

Just add C_abs with its transposed version -

G = C_abs + C_abs.T

To understand, look at the computation part of the code :

G[i,j] = C_abs[i,j]+C_abs[j,i]

The first input on the right side is C_abs[i,j], which has the same iterators involved as on the left side of the assignment - G[i,j]. So, for a vectorized solution, we will use it without change as the first input. The second input on the right side is C_abs[j,i] and its iterators are flipped version of the iterators on the left side - G[i,j]. This flipping in the entire array context would be the transpose of C_abs. Therefore, put together, we will add C_abs with its own transposed version to get the desired output in a vectorized manner.

Upvotes: 5

Related Questions