In an Octave session:
>> a=[1 2 3;4 5 6;7 8 9]
a =
1 2 3
4 5 6
7 8 9
>> b=[1, 4, 8]
b =
1 4 8
>> a(b)
ans =
1 2 6
This isn't the kind of behavior that I recall getting in MATLAB, but then I'm not in the habit of using index values greater than the dimensions. Evidently it is picking the items in a flattened matrix
>> reshape(a,1,9)
ans =
1 4 7 2 5 8 3 6 9
>> reshape(a,1,9)(b)
ans =
1 2 6
In Python/numpy indexing is done with []
instead of ()
. It is also 0 based, not 1.
In [56]: a = np.arange(1,10).reshape(3,3)
In [57]: a
Out[57]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [58]: b=[0,3,7]
In [59]: a.ravel(order='F')[b]
Out[59]: array([1, 2, 6])
In [60]: a.ravel(order='F')
Out[60]: array([1, 4, 7, 2, 5, 8, 3, 6, 9])
To get the same values in numpy
I had to specfify order F
when flattening the array. That way it 'scans' the values in the column major order that MATLAB uses.
Without the order F
, the default scan order is row major:
In [61]: a.ravel()
Out[61]: array([1, 2, 3, 4, 5, 6, 7, 8, 9])
In [62]: a.ravel()[b]
Out[62]: array([1, 4, 8])
I could also get the order F when initially reshaping a
:
In [67]: a = np.arange(1,10).reshape(3,3,order='F')
In [68]: a
Out[68]:
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
In [69]: a.flat[b]
Out[69]: array([1, 2, 6])
===
In MATLAB/Octave, we can get the 2d indices with:
>> [r,c] = ind2sub([3,3],b)
r =
1 1 2
c =
1 2 3
>> a(1,1), a(1,2), a(2,3)
ans = 1
ans = 2
ans = 6
The same unraveling in numpy
(applied to the order F version of a
):
In [75]: np.unravel_index(b, (3,3))
Out[75]: (array([0, 1, 2]), array([0, 0, 1]))
In [76]: a[_] # using the Out[75] line as index
Out[76]: array([1, 2, 6])
In [77]: a[0,0],a[1,0],a[2,1] # equivalently
Out[77]: (1, 2, 6)