1

I've got a simple problem and I can't figure out how to solve it.

Here is a matrix: A = np.array([[1,0,3],[0,7,9],[0,0,8]]).

I want to find a quick way to replace all elements of this matrix by their inverses, excluding of course the zero elements.

I know, thanks to the search engine of Stackoverflow, how to replace an element by a given value with a condition. On the contrary, I do not figure out how to replace elements by new elements depending on the previous ones (e.g. squared elements, inverses, etc.)

Srivatsan
  • 9,225
  • 13
  • 58
  • 83
xeladsn
  • 15
  • 1
  • 5

2 Answers2

5

Use 1. / A (notice the dot for Python 2):

>>> A
array([[1, 0, 3],
       [0, 7, 9],
       [0, 0, 8]], dtype)
>>> 1./A
array([[ 1.        ,         inf,  0.33333333],
       [        inf,  0.14285714,  0.11111111],
       [        inf,         inf,  0.125     ]])

Or if your array has dtype float, you can do it in-place without warnings:

>>> A = np.array([[1,0,3], [0,7,9], [0,0,8]], dtype=np.float64)
>>> A[A != 0] = 1. / A[A != 0]
>>> A
array([[ 1.        ,  0.        ,  0.33333333],
       [ 0.        ,  0.14285714,  0.11111111],
       [ 0.        ,  0.        ,  0.125     ]])

Here we use A != 0 to select only those elements that are non-zero.

However if you try this on your original array you'd see

array([[1, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

because your array could only hold integers, and inverse of all others would have been rounded down to 0.


Generally all of the numpy stuff on arrays does element-wise vectorized transformations so that to square elements,

>>> A = np.array([[1,0,3],[0,7,9],[0,0,8]]) 
>>> A * A
array([[ 1,  0,  9],
       [ 0, 49, 81],
       [ 0,  0, 64]])
3

And just a note on Antti Haapala's answer, (Sorry, I can't comment yet) if you wanted to keep the 0's, you could use

B=1./A #I use the 1. to make sure it uses floats
B[B==np.inf]=0
sbrass
  • 905
  • 7
  • 12