如何将方阵分割成没有循环的立方体

问题描述 投票:0回答:1

我正在努力在不使用循环的情况下分割矩阵。我想将 9x9 矩阵拆分为 9 个 3x3 矩阵(不重叠)。我尝试使用

split()
传递向量作为“因子”分组,但没有成功。也尝试使用
asplit()
但没有成功。我想我不明白“MARGIN”在
asplit()
上是如何工作的。我可以使用循环获得 3x3“立方体”,但我只是想知道是否有一种方法可以使用简单的实用函数来做到这一点。

m <- matrix(1:81, 9, 9)

我想将 9 个结果 3x3 矩阵存储在一个列表中。第一个立方体的预期结果是:

cube[[1]]

     [,1] [,2] [,3]
[1,]   01   10   19
[2,]   02   11   20
[3,]   03   12   21

我试过了

# all these split by row
indices <- matrix(1:9, 3, 3)
cubes <- split(m, as.vector(indices))

indices <- array(1:9, dim = c(3, 3, 9))
cubes <- split(m, as.vector(indices))

indices <- array(matrix(1:9, 3, 3), dim = c(3, 3, 9))
cubes <- split(m, as.vector(indices))

# this gives an error
asplit(m, MARGIN = c(3,1))
r matrix
1个回答
0
投票

这可能不是最有效的方法,但它应该有效

## utility function to assign (1,2,3) -> 1, (4,5,6) -> 2, etc.
f <- function(x) (x-1) %/% 3 + 1
## create factor from (row-block, col-block) interaction
g <- interaction(f(row(m)), f(col(m)))
## split and convert back to matrices
lapply(split(m, g), \(x) matrix(x, nrow = 3))
© www.soinside.com 2019 - 2024. All rights reserved.