[SciPy-user] Vector indexing

Pau Gargallo pau.gargallo at gmail.com
Mon Jun 5 08:51:29 CDT 2006


On 6/5/06, David Grant <david.grant at telus.net> wrote:
> On Sunday 04 June 2006 17:17, Robert Kern wrote:
> > David Grant wrote:
> > > Vector indexing question:
> > >
> > > a=rand(10,10)
> > >
> > > 1) a[0:3, 0:3] #gives me the first 3 rows and columns
> > >
> > > 2) a[range(2),range(2)] gives me a one-dimensional array of elements
> > > [0,0], [1,1], [2,2]
> >
> > Actually, it gets you array([a[0,0], a[1,1]]).
>
> There I go again with my 1-indexed arrays...thanks Matlab. ;-)
>
> > > How do I do 1) using some on-the-fly generated array?
> >
> > Slice objects.
> >
> > >>> a[slice(0, 3), slice(0, 3)]
> >
> > array([[ 0.83840663,  0.36944056,  0.48230632],
> >        [ 0.04508558,  0.25772124,  0.62787961],
> >        [ 0.0455162 ,  0.69427227,  0.26374691]])
>
> But let's say that you didn't want a slice, but you wanted to grab some random
> rows and columns. Simon's solution seems to do the trick: a[x,:][:,y] which I
> guess is just performing indexing on it twice.
>
> Dave
>

a[ ix_(x,y) ] also works.
ix_ is useful when the number of dimensions is unknown at coding time.

pau



More information about the SciPy-user mailing list