sandikou
sandikou

Reputation: 133

How to extract n-1 dimension array from a n-dimension array thanks to a n-1 dimension array and without a loop?

My problem is pretty simple, but I can not seem to find a solution. I have a n-dimension array A, and I would like to extract the n-1 dimension array B thanks to a n-1 dimension array of indices C. How could I do it, without a loop ?

For example :

A=array(1:12, dim=c(2,3,2))
A
, , 1
      [,1] [,2] [,3]
 [1,]    1    3    5
 [2,]    2    4    6

  , , 2
       [,1] [,2] [,3]
 [1,]    7    9   11
 [2,]    8   10   12

C=array(c(1,2,2,1,1,2),dim=c(2,3))
C
      [,1] [,2] [,3]
 [1,]    1    2    1
 [2,]    2    1    2

and finally I would like to find B (as something like "A[,,C]")

B
      [,1] [,2] [,3]
 [1,]    1    9    5
 [2,]    8    4    12

As if I have done

B 
           [,1]                 [,2]              [,3]
 [1,]    A[1,1,C[1,1]]   A[1,2,C[1,2]    A[1,3,C[1,3]]
 [2,]    A[2,1,C[2,1]]   ...

I have to do this in 5 dimensions, so if I could avoid to make loops...

Thanks.

Upvotes: 3

Views: 112

Answers (3)

akrun
akrun

Reputation: 887691

You could also try

library(reshape2)
matrix(A[as.matrix(melt(C))], ncol=ncol(C))
#      [,1] [,2] [,3]
#[1,]    1    9    5
#[2,]    8    4   12

Upvotes: 3

nicola
nicola

Reputation: 24500

Another solution:

B<-A[cbind(c(row(C)),c(col(C)),c(C))]
dim(B)<-dim(C)

Upvotes: 3

Patrick Roocks
Patrick Roocks

Reputation: 3259

I would solve this by index calculation: By adding 0:(length(C)-1) to every [.,.,i]-slice (i=1,2 in your case) of A you get the indices for the first slice. If a multiplication of C-1 with the length of C is done before and then 1 added, you will also get the correct indices of all other slices. The -1 and +1 operations compensate each other, hence we can express this very shortly:

ind <- as.vector((C-1) * length(C) + 1:length(C))
array(A[ind], dim = dim(C))

Upvotes: 4

Related Questions