Numpy: unexpected result when dividing a vertical matrix by one of its own elements

So, I created a numpy vertical array, used the / = operator, and the result seems to be wrong. Basically, if x is a vector, s is a scalar. I would expect x / = s to have every element x divided by s. However, I could not understand the meaning of the conclusion. The operator applies only to part of the elements in x, and I'm not sure how they are selected.

In [8]: np.__version__ Out[8]: '1.10.4' In [9]: x = np.random.rand(5,1) In [10]: x Out[10]: array([[ 0.47577008], [ 0.66127875], [ 0.49337183], [ 0.47195985], [ 0.82384023]]) #### In [11]: x /= x[2] In [12]: x Out[12]: array([[ 0.96432356], [ 1.3403253 ], [ 1. ], [ 0.95660073], [ 0.82384023]]) #### this entry is not changed. 
+7
python arrays numpy
source share
2 answers

Your x [2] value changes to 1 in the middle of the rating. you need to make a copy of the value, then divide each element into it, either assign it to another variable, or use a copy of ie

 from copy import copy x /= copy(x[2]) 

To understand why we need to do this, you can look under the hood of what is happening.

 In [9]: x = np.random.rand(5,1) 

Here we define x as an array, but it is not entirely clear that each element in this array is also technically an array. This is an important difference, since we are not dealing with specific values, not massive array objects, so the next line:

 In [11]: x /= x[2] 

We end up looking up at the value in x [2], which returns an array with one value, but because we look at it every time whenever possible.

A cleaner solution would be to smooth the array by 1d, so x [2], now equal to 0.49337183 instead of the array ([0.49337183])

So, before we do x /= x[2] , we can call x = x.flatten()

Or better yet, keep 1d from the start of x = np.random.rand(5)

And as for the fact that x [3] changes, but x [4] does not, the only real useful answer I can give is that division does not occur in order, complicated wimey time-buffering.

+6
source share

This is only for an odd vector size in theory, but if you do: x = np.random.rand(5,1) a = x[2]*1 x/=a it will work

0
source share

All Articles