Skip to content Skip to sidebar Skip to footer

Access Elements From Matrix In Numpy

I have a matrix A mXn and an array of size m The array indicates the index of column which has to be index from A. So, an example would A = [[ 1,2,3],[1,4,6],[2,9,0]] indices = [

Solution 1:

Use advanced indexing:

A = np.array([[ 1,2,3],[1,4,6],[2,9,0]])
indices = np.array([0,2,1])

# here use an array [1,2,3] to represent the row positions, and combined with indices as
# column positions, it gives an array at corresponding positions (1, 0), (2, 2), (3, 1)
A[np.arange(A.shape[0]), indices]
# array([1, 6, 9])

Solution 2:

A = np.array([[ 1,2,3],[1,4,6],[2,9,0]])

indices = [0,2,1]
m=range(0,A.shape[0])
for b in zip(m,indices):
    print A[b]

output:
1
6
9

Post a Comment for "Access Elements From Matrix In Numpy"