Skip to content
Prev 68588 / 398506 Next

Index matrix to pick elements from 3-dimensional matrix

I'm assuming what you want to do is randomly sample from slices of A 
selected on the 3-rd dimension, as specified by J.  Here's a way that 
uses indexing by a matrix.  The cbind() builds a three column matrix of 
indices, the first two of which are randomly selected.  The use of 
replace() is to make the result have the same attributes, e.g., dim and 
dimnames, as J.

 > A <- array(letters[1:12],c(2,2,3))
 > J <- matrix(c(1,2,3,3),2,2)
 > replace(J, TRUE, A[cbind(sample(dim(A)[1], length(J), rep=T), 
sample(dim(A)[2], length(J), rep=T), as.vector(J))])
      [,1] [,2]
[1,] "b"  "l"
[2,] "f"  "k"
 > replace(J, TRUE, A[cbind(sample(dim(A)[1], length(J), rep=T), 
sample(dim(A)[2], length(J), rep=T), as.vector(J))])
      [,1] [,2]
[1,] "b"  "l"
[2,] "h"  "i"
 > replace(J, TRUE, A[cbind(sample(dim(A)[1], length(J), rep=T), 
sample(dim(A)[2], length(J), rep=T), as.vector(J))])
      [,1] [,2]
[1,] "c"  "l"
[2,] "h"  "k"
 >

-- Tony Plate
Robin Hankin wrote: