Home > Back-end >  Accessing numpy array using 2 arrays like in MATLAB
Accessing numpy array using 2 arrays like in MATLAB

Time:03-20

I'm trying to replicate the following code from MATLAB in Python:

X = [1,2,3;
    4,5,6];
idx = [2,1];
idy = [3,2];

x = X(idx,idy)

Output: x = [6,5;3,2]

I wish it was as simple as:

X = np.array([[1,2,3],[4,5,6]])
idx = np.array([1,0])
idy = np.array([2,1])

x = X[idx,idy]

but that is not the case.

What am I missing?

CodePudding user response:

Just add the type of values inside the array and you are good to go. fixing your 2nd example would be:

import numpy as np

X = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
idx = np.array([1,0], np.int32)
idy = np.array([2,1], np.int32)
x = X[idx,idy]

print(x)

with output:

[6 2]

as expected..

CodePudding user response:

MATLAB automatically indexes the cross product.

The numpy equivalent is np.ix_:

Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].

>>> X[np.ix_(idx, idy)]
# array([[6, 5],
#        [3, 2]])

Or as Michael commented, you can index each dimension explicitly:

>>> X[idx][:, idy]
# array([[6, 5],
#        [3, 2]])
  • Related