[Numpy-discussion] Can not update a submatrix
Nadav Horesh
nadavh@visionsense....
Thu Jan 31 05:21:31 CST 2008
Thanks for your explanation. It explains also the following:
>>> R = N.arange(9).reshape(3,3)
>>> ax = [0,2]
>>> U = R[ax,:]
>>> U
array([[0, 1, 2],
[6, 7, 8]])
>>> U[:] = 100
>>> U
array([[100, 100, 100],
[100, 100, 100]])
>>> R # No change since U is a copy
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> R[ax,:] = 100 # Works through __setitem__
>>> R
array([[100, 100, 100],
[ 3, 4, 5],
[100, 100, 100]])
Nadav
On Wed, 2008-01-30 at 13:35 -0700, Timothy Hochberg wrote:
>
>
>
> On Jan 30, 2008 12:43 PM, Anne Archibald <peridot.faceted@gmail.com>
> wrote:
>
> On 30/01/2008, Francesc Altet <faltet@carabos.com> wrote:
> > 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:
>
>
>
> This is not exactly correct.
>
>
> [...a fine explanation by Anne...]
>
> Another way to look at this is note that:
>
>
> R[ax,:][:,ax] = 100
>
>
>
> is translated to:
>
>
>
> R.__getitem__((ax, :)).__setitem__((:,ax), 100)
>
>
>
> '__setitem__' is capable of setting values using fancy indexing, but
> as has been noted, '__getitem__' makes a copy of R when using fancy
> indexing, and therefore the original does not get modified.
>
> [Technically, ':' gets translated to slice(None,None,None), but I
> didn't want to write that out].
>
> --
> . __
> . |-\
> .
> . tim.hochberg@ieee.org
>
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20080131/102e9f08/attachment.html
More information about the Numpy-discussion
mailing list