juniper-
juniper-

Reputation: 6562

numpy 3D indexing by list

Why do these different ways of indexing into X return different values?

print vertices[0]
print X[vertices[0]]
print X[tuple(vertices[0])]
print X[vertices[0][0]], X[vertices[0][1]], X[vertices[0][2]]
print [X[v] for v in vertices[0]]

And the output:

[(0, 2, 3), (0, 2, 4), (0, 3, 3)]
[-1.         -0.42857143  0.14285714]
[-1.         -0.42857143  0.14285714]
-0.428571428571 -0.428571428571 -0.142857142857
[-0.4285714285714286, -0.4285714285714286, -0.1428571428571429]

How can I use vertices[0] to get the output in the last line?

Upvotes: 0

Views: 82

Answers (2)

gboffi
gboffi

Reputation: 25023

If you had used four vertices instead of three, writing

vertices = [[(0, 2, 3), (0, 2, 4), (0, 3, 3), (3,3,3)],]

followed by

print X[tuple(vertices[0])]

then the error message

IndexError: too many indices for array

would have shown that the right way to go is

print X[zip(*vertices[0])]

or definining the elements of vertices like

# rtices[0] = [(0, 2, 3), (0, 2, 4), (0, 3, 3), (3,3,3)]
#        4 different i's    4 j's      4 k's
vertices[0] = [(0,0,0,3), (2,2,3,3), (3,4,3,3)]

Upvotes: 1

Irshad Bhat
Irshad Bhat

Reputation: 8709

The thing is :

X[tuple(vertices[0])]

takes:

X[0][0][0],X[2][2][3],x[3][4][3]

while in:

X[[vertices[0][0]], X[vertices[0][1]], X[vertices[0][2]]]

vertices[0][0],[vertices[0][0],[vertices[0][0] are all same = 0, i.e. why different results than previous ones.

Upvotes: 0

Related Questions