You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用循环将方阵拆分为子矩阵块(R语言)

拆分9×9矩阵为9个3×3子矩阵(无循环实现)

问题需求

将9×9矩阵拆分为9个不重叠的3×3子矩阵,存储在列表中,要求不使用显式循环,尝试过split()和asplit()但未成功,希望通过工具函数实现。

示例矩阵:

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

预期第一个子块结果:

cube[[1]]

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

过往尝试(未成功)

# 这些尝试均按行拆分,不符合需求
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))

# 此代码报错,原因为MARGIN参数超出矩阵维度
asplit(m, MARGIN = c(3,1))

解决方案

方法一:构造分组矩阵配合split()

核心是生成每个元素对应的子块编号矩阵,以此作为分组依据拆分,再将拆分后的向量转换为3×3矩阵:

# 生成子块编号矩阵:每个3×3区域对应唯一编号1-9
group_matrix <- matrix(rep(rep(1:3, each=3), 3), nrow=9, byrow=TRUE) +
  rep(0:2*3, each=3)

# 按分组拆分矩阵
cubes <- split(m, group_matrix)

# 将每个分组的向量转换为3×3矩阵
cubes <- lapply(cubes, matrix, nrow=3, ncol=3)

方法二:数组重塑配合asplit()

利用数组的高维特性,先将原矩阵重塑为包含子块的高维数组,再通过asplit()按子块维度拆分:

# 将9×9矩阵重塑为3×3×3×3的数组:前两维是子块的行/列,后两维是子块的位置(行/列方向)
arr <- array(m, dim = c(3, 3, 3, 3))

# 调整维度顺序并合并为3×3×9的数组,第3维度对应9个子块
arr <- aperm(arr, c(1, 2, 3, 4))
arr <- array(arr, dim = c(3, 3, 9))

# 按第3维度拆分,得到9个3×3矩阵的列表
cubes <- asplit(arr, MARGIN = 3)

内容的提问来源于stack exchange,提问作者guasi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 12:33:15