[Numpy-discussion] Can not update a submatrix

Francesc Altet faltet@carabos....
Wed Jan 30 09:08:02 CST 2008


A Wednesday 30 January 2008, Nadav Horesh escrigué:
> In the following piece of code:
> >>> import numpy as N
> >>> R = N.arange(9).reshape(3,3)
> >>> ax = [1,2]
> >>> R
>
> array([[0, 1, 2],
>        [3, 4, 5],
>        [6, 7, 8]])
>
> >>> R[ax,:][:,ax] = 100
> >>> R
>
> array([[0, 1, 2],
>        [3, 4, 5],
>        [6, 7, 8]])
>
> Why R is not updated?

Because R[ax] is not a view of R, but another copy of the original 
object (fancy indexing does return references to different objects).  
In order to get views, you must specify only a slice of the original 
array.  For example:

In [50]: S = R[::2]
In [51]: S[:] = 2
In [52]: R
Out[52]:
array([[2, 2, 2],
       [3, 4, 5],
       [2, 2, 2]])

So, what you need is something like:

In [68]: R = N.arange(9).reshape(3,3)
In [69]: S = R[1:3,:][:,1:3]
In [70]: S[:] = 2
In [71]: R
Out[71]:
array([[0, 1, 2],
       [3, 2, 2],
       [6, 2, 2]])

Cheers,

-- 
>0,0<   Francesc Altet     http://www.carabos.com/
V   V   Cárabos Coop. V.   Enjoy Data
 "-"


More information about the Numpy-discussion mailing list