0

I need to extract one element from each column of a matrix according to an index vector. Say:

index = [0,1,1]
matrix = [[1,4,7],[2,5,8],[3,6,9]]

Index vector tells me I need the first element from column 1, second element from column 2, and third element from column 3.

The output should be [1,5,8]. How can I write it out without explicit loop?

Thanks

3
  • Your example seems pretty non-general. What about an index vector like [0, 2]? What about [0, 0, 1, 2]? Should these also be covered? Commented Aug 28, 2018 at 16:37
  • No need for considering this. Dim of index vector is equal to number of columns of matrix Commented Aug 28, 2018 at 16:54
  • I change the index vector, which is first one from column 1, the second from column 2 and 3 Commented Aug 28, 2018 at 16:56

3 Answers 3

4

You can use advanced indexing:

index = np.array([0,1,2])
matrix = np.array([[1,4,7],[2,5,8],[3,6,9]])

res = matrix[np.arange(matrix.shape[0]), index]
# array([1, 5, 9])

For your second example, reverse your indices:

index = np.array([0,1,1])
matrix = np.array([[1,4,7],[2,5,8],[3,6,9]])

res = matrix[index, np.arange(matrix.shape[1])]
# array([1, 5, 8])
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot. It works. But I need to select w.r.t columns. This one works for rows.
@MichaelSun, Can you be clearer? The output is [1, 5, 9] as per desired output in your question.
V0.15 has added a np.take_along_axis function that does this kind of indexing. It's interesting reading.
@hpaulj, Thanks, I definitely need to upgrade!
2

Since you're working with 2-dimensional matrices, I'd suggest using numpy. Then, in your case, you can just use np.diag:

>>> import numpy as np
>>> matrix = np.array([[1,4,7],[2,5,8],[3,6,9]])
>>> matrix
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])
>>> np.diag(matrix)
array([1, 5, 9])

However, @jpp's solution is more generalizable. My solution is useful in your case because you really just want the diagonal of your matrix.

2 Comments

I should make question more clear. That one is just one example. I need more general thing like get i,j,k element from three columns respectively
Then you should go with @jpp's solution.
1
val = [matrix[i][index[i]] for i in range(0, len(index))]

1 Comment

I think OP said How can I write it out without explicit loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.