Strickland
Strickland

Reputation: 600

Quickly accessing matrix element, where indices are given by other matrices

I am given a matrix M. I now need to determine a matrix of the same dimension, which is defined by

N_{i,j} = M_{A(i,j),B(i,j)}

for two matrices A and B of the same dimension, which define indices.

As an example,

set.seed(1)
M <- matrix(LETTERS[1:(4*6)], ncol=6)
A <- matrix(sample(c(1:4), 4*6, replace=TRUE), ncol=6)
B <- matrix(sample(c(1:6), 4*6, replace=TRUE), ncol=6)

How do I now quickly determine N?

Upvotes: 1

Views: 44

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269694

Try this:

replace(M, TRUE, M[cbind(c(A), c(B))])

or

array(M[cbind(c(A), c(B))], dim(M))

Upvotes: 2

Related Questions