Skip to content
Advertisement

Faster matrix calculation in numpy

Is there some faster variant of computing the following matrix (from this paper), given a nxn matrix M and a n-vector X: G_ij = sqrt(M_ij^2 + ((X_i - X_j)/M_ij)^2 + 2X_i^2 + 2X_j^2)/2 ?

I currently compute it as follows:

JavaScript

This is very slow, but I suspect there is a nicer “numpythonic” way of doing this instead of looping…

EDIT: While all answers work and are much faster than my naive implementation, I chose the one I benchmarked to be the fastest. Thanks!

Advertisement

Answer

Quite straightforward actually.

JavaScript

Your code and result:

JavaScript
JavaScript

Using broadcasting:

JavaScript
JavaScript

Note that you did not use the formula directly for diagonal elements and only computed for upper triangular region of G. I simply implemented the formula to calculate all G[i, j].

Note: If diagonal elements of M don’t matter and they contain some zeros, just add some offset to avoid the divide by zero error like:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement