如何用m *(n-i)维矩阵切割n维数组,保持一些尺寸自由?

时间:2015-08-11 16:57:56

标签: r slice

如果我有一个 n 维数组,可以通过 m * n 矩阵进行切片

a <- array(1:27,c(3,3,3))

b <- matrix(1:3,3,3)

# This will return the index a[1,1,1] a[2,2,2] and a[3,3,3]
# That is one result for each row in the b matrix
a[b]

# Output
[1]  1 14 27

在上面的例子中,数组a的切片方式与b矩阵中每一行切片相同,结果合并。

有没有&#34;有效且容易的&#34;如何做一个类似的切片,但保持一些尺寸免费? 那就是用 m * (ni)维数组切割一个维数组,得到一个 i + 1 维数组。

# sliceem
# Function for slicing 
# Parameters
#   a - The n dimensional array to slice
#   b - A m*(n-i) matrix 
#   freeDimension - A vector of length i with dimensions to keep free 
#                    during the slicing
# Returns
#   A i dimensional array where the first dimension have m elements and
#   each element in the first dimension correspond to a slice using
#   a row in the b matrix

#### Examples of desired behavior ####

a <- array(1:27,c(3,3,3))

b <- matrix(1:2,2,2)


sliceem(a,b,freeDimension=2)
# Output (a[1,,1] and a[2,,2])
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]   11   14   17


sliceem(a,b,freeDimension=1)
# Output a[,1,1] and a[,2,2]
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]   13   14   15




b <- matrix(1:2,2,1)
sliceem(a,b,freeDimension=c(2,3))

# Output (a[1,,] and a[2,,]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8

, , 2

     [,1] [,2] [,3]
[1,]   10   13   16
[2,]   11   14   17

, , 3

     [,1] [,2] [,3]
[1,]   19   22   25
[2,]   20   23   26

0 个答案:

没有答案