I am trying to find a simple numpy command to take the values of an 3D matrix according to an index array for the second coordinate. This can be done as:
import numpy as np
entry = np.array([[1, 2],[3,4],[5, 6]])
entries = np.stack([entry, entry, entry, entry])
indices = np.array([2, 1, 0, 1])
r = np.array([entries[i, indices[i], :] for i in range(len(indices))])
This code produces the correct result but uses list comprehension instead of a single command.
Is there a numpy operation that does the same? I expected np.take() to work, but it does not as it produces an array of shape (4, 4, 2) instead of (4, 2)
entries[np.arange(indices.size), indices, :]