tags:

views:

151

answers:

2

Let's suppose I have a numpy matrix variable called MATRIX with 3 coordinates: (x, y, z).

Is acessing the matrix's value through the following code

myVar = MATRIX[0,0,0]

equal to

myVar = MATRIX[0,0][0]

or

myVar = MATRIX[0][0,0]

?

What about if I have the following code?

myTuple = (0,0)
myScalar = 0
myVar = MATRIX[myTuple, myScalar]

Is the last line equivalent to doing

myVar = MATRIX[myTuple[0], myTuple[1], myScalar]

I have done simple tests and it seems so, but maybe that is not so in all the cases. How do square brackets work in python with numpy matrices? Since day one I felt confused as how they work.

Thanks

+1  A: 

It's not possible to index a tuple with another tuple, so none of that code is valid.

Alex Gaynor
+4  A: 

I assume you have a array instance rather than a matrix, since the latter only can have two dimensions.

m[0, 0, 0] gets the element at position (0, 0, 0). m[0, 0] gets a whole subarray (a slice), which is itself a array. You can get the first element of this subarray like this: m[0, 0][0], which is why both syntaxes work (even though m[i, j, k] is preferred because it doesn't have the unnecessary intermediate step).

Take a look at this ipython session:

rbonvall@andy:~$ ipython
Python 2.5.4 (r254:67916, Sep 26 2009, 08:19:36) 
[...]

In [1]: import numpy.random

In [2]: m = numpy.random.random(size=(3, 3, 3))

In [3]: m
Out[3]: 
array([[[ 0.68853531,  0.8815277 ,  0.53613676],
        [ 0.9985735 ,  0.56409085,  0.03887982],
        [ 0.12083102,  0.0301229 ,  0.51331851]],

       [[ 0.73868543,  0.24904349,  0.24035031],
        [ 0.15458694,  0.35570177,  0.22097202],
        [ 0.81639051,  0.55742805,  0.5866573 ]],

       [[ 0.90302482,  0.29878548,  0.90705737],
        [ 0.68582033,  0.1988247 ,  0.9308886 ],
        [ 0.88956484,  0.25112987,  0.69732309]]])

In [4]: m[0, 0]
Out[4]: array([ 0.68853531,  0.8815277 ,  0.53613676])

In [5]: m[0, 0][0]
Out[5]: 0.6885353066709865

It only works like this for numpy arrays. Python built-in tuples and lists are not indexable by tuples, just by integers.

Roberto Bonvallet
hmm, and what would m[0,0,0] yield?
devoured elysium
The same as `m[0, 0][0]`, given that `len(m.shape) == 3`.
Roberto Bonvallet