# [Numpy-discussion] Is there a way that indexing a matrix of data with a matrix of indices?

ZHUO QL (KDr2) zhuoql at yahoo.com
Thu Nov 30 00:56:57 EST 2017

```Thank you all, all of these methods work well  :)

----
ZHUO QL (KDr2) http://kdr2.com

On Thursday, November 30, 2017, 2:26:16 AM GMT+8, Eric Hermes <ehermes at chem.wisc.edu> wrote:

On Wed, 2017-11-29 at 12:00 -0500, numpy-discussion-request at python.org
wrote:
> Date: Wed, 29 Nov 2017 14:56:28 +0000 (UTC)
> From: "ZHUO QL (KDr2)" <zhuoql at yahoo.com>
> To: Discussion of Numerical Python <numpy-discussion at python.org>
> Subject: [Numpy-discussion] Is there a way that indexing a matrix of
>     data with a matrix of indices?
> Message-ID: <360382279.3966234.1511967388050 at mail.yahoo.com>
> Content-Type: text/plain; charset="utf-8"
>
> Hi, all
> suppose:
> - D, is the data matrix, its shape is? M x N- I, is the indices
> matrix, its shape is M x K,? K<=N
> Is there a efficient way to get a Matrix R with the same shape of I
> so that R[x,y] = D[x, I[x,y]] ?
> A nested for-loop or list-comprehension is too slow for me.??
> Thanks.

I don't know if this will be substantially faster, but you can try the
following:

I += np.array(range(M))[:, np.newaxis] * N
R = D.ravel()[I.ravel()].reshape((M, K))

Eric

> ----
> ZHUO QL (KDr2) http://kdr2.com
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: <http://mail.python.org/pipermail/numpy-