[Numpy-discussion] Can not update a submatrix
Timothy Hochberg
tim.hochberg at ieee.org
Wed Jan 30 15:35:50 EST 2008
On Jan 30, 2008 12:43 PM, Anne Archibald <peridot.faceted at gmail.com> wrote:
> On 30/01/2008, Francesc Altet <faltet at 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 at ieee.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20080130/219b537d/attachment.html>
More information about the NumPy-Discussion
mailing list