0

I have a rank two array, and would like to use slices to index it. If I create the slices in place, I get the expected result:

A = rand(3,3)
assert(allclose(A[0:3, 0:3], A))

On the other hand, if I create the slices in advance, indexing does not behave as expected (at least from the perspective of an octave/matlab user, where both methods produce the same result):

A = rand(3,3)
i = range(0,3)
j = range(0,3)
assert(allclose(A[i, j], A))
# AssertionError

Why do these methods produce different results?

Kurohige
  • 1,378
  • 2
  • 16
  • 24
  • Another recent numpy indexing question along the same line: https://stackoverflow.com/questions/55106996/numpy-array-weird-indexing-explanation – hpaulj Mar 11 '19 at 21:22

1 Answers1

0

Why do you expect them to do the same thing? numpy is different from MATLAB with this kind of indexing.

In [6]: arr = np.arange(9).reshape(3,3)

In [7]: arr[range(3),range(3)]
Out[7]: array([0, 4, 8])

With the range (or a list or array of the same values), it returns a 1d array, in this case the diagonal of the 2d array. This indexing picks a set of points, not a block.

In numpy if you want a 2d result with 'advanced indexing' you need to create a pair of indexing arrays that together broadcast to the right shape:

In [8]: arr[np.arange(3)[:,None],range(3)]
Out[8]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

In MATLAB/octave it's easy to select a block, but much harder to select individual elements.

arr(sub2ind([3,3],[1,2,3],[1,2,3]))

In general, to understand numpy advanced indexing you need to understand broadcasting - which applies to indexing as well as to math operations like addition.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • *Why do you expect them to do the same thing*: I was confused about `A[0:3, 0:3]` being treated differently from `A[range(3), range(3)]`. – Joseph Greenpie Mar 11 '19 at 22:36
  • The numpy documentation distinguishes between `basic` indexing and `advanced`. Indexing with slices (the colon) and lists are quite different in behavior. – hpaulj Mar 11 '19 at 22:54