Mollifier - 1 year ago 51

R Question

i want to subset a 3-dimensional array with three matrices where each matrix represents one dimension.

An example:

`set.seed(1)`

A = array(sample(1:10,24, replace=TRUE), dim=c(3,4,2))

ind_dimension1 = matrix(c(1,3,2,1), nrow=2)

ind_dimension2 = matrix(c(4,3,2,1), nrow=2)

ind_dimension3 = matrix(c(1,2,2,1), nrow=2)

As result i want a matrix with the same dimension as the subsetting matrices, i.e. 2x2:

`# A[1,4,1](=1) A[2,2,2](=8)`

# A[3,3,2](=10) A[1,1,1](=3)

In Matlab this can be done by:

`A(sub2ind(size(A), ind_dimension1, ind_dimension2, ind_dimension3))`

With two dimensions, i.e.

`A2=A[,,1]`

`sub2ind(size(A2), ind_dimension1, ind_dimension2)`

`(ind_dimension2-1)*dim(A2)[2]+ind_dimension1`

Thanks in advance.

Answer Source

How about this?

```
myMat <- matrix(A[cbind(c(ind_dimension1),
c(ind_dimension2),
c(ind_dimension3))],
dim(ind_dimension1))
myMat
[,1] [,2]
[1,] 1 8
[2,] 10 3
```

This uses matrix subsetting (see `help("[")`

) to extract the desired elements. The dimension matrices are turned into vectors with `c`

, and then recombined into a matrix with `cbind`

that is used to extract from the array. The resulting vector is fed to `matrix`

and the desired dimensions are produces with `dim`

.