gpt4 book ai didi

arrays - 将矩阵并排放置以创建另一个矩阵

转载 作者:行者123 更新时间:2023-12-02 09:08:08 25 4
gpt4 key购买 nike

我有一个由 12 个矩阵组成的数组,由以下代码给出:

ma = array(sample(0:127,3*4*6,replace=TRUE), c(3,4,12))

让他们被命名为A、B、C...L

我想创建一个矩阵,其中上述矩阵以 4 行 * 3 列的模式排列:

ABC
DEF
GHI
JKL

所以最终的矩阵将有 12 行和 12 列。

我可以执行以下代码:

rbind(cbind(m[,,1],m[,,2],m[,,3]),
cbind(m[,,4],m[,,5],m[,,6]),
cbind(m[,,7],m[,,8],m[,,9]),
cbind(m[,,10],m[,,11],m[,,12]))

但我无法为此编写通用函数:

matbinder(ma,n)   

其中 ma 是输入矩阵数组,n 是要放入一行的初始矩阵的数量(本例中为 3)。

最佳答案

我将使用它作为示例矩阵,因为它将按照您喜欢的顺序包含所有字母

ma = array(as.vector(t(outer(letters[1:12],1:12, FUN=paste0))), c(3,4,12))

然后你可以像这样进行转换

a<-ma
dim(a) <- c(3,12,4)
apply(a,2,c)

产生

      [,1] [,2] [,3] [,4]  [,5] [,6] [,7] [,8]  [,9] [,10] [,11] [,12]
[1,] "a1" "a4" "a7" "a10" "b1" "b4" "b7" "b10" "c1" "c4" "c7" "c10"
[2,] "a2" "a5" "a8" "a11" "b2" "b5" "b8" "b11" "c2" "c5" "c8" "c11"
[3,] "a3" "a6" "a9" "a12" "b3" "b6" "b9" "b12" "c3" "c6" "c9" "c12"
[4,] "d1" "d4" "d7" "d10" "e1" "e4" "e7" "e10" "f1" "f4" "f7" "f10"
[5,] "d2" "d5" "d8" "d11" "e2" "e5" "e8" "e11" "f2" "f5" "f8" "f11"
[6,] "d3" "d6" "d9" "d12" "e3" "e6" "e9" "e12" "f3" "f6" "f9" "f12"
[7,] "g1" "g4" "g7" "g10" "h1" "h4" "h7" "h10" "i1" "i4" "i7" "i10"
[8,] "g2" "g5" "g8" "g11" "h2" "h5" "h8" "h11" "i2" "i5" "i8" "i11"
[9,] "g3" "g6" "g9" "g12" "h3" "h6" "h9" "h12" "i3" "i6" "i9" "i12"
[10,] "j1" "j4" "j7" "j10" "k1" "k4" "k7" "k10" "l1" "l4" "l7" "l10"
[11,] "j2" "j5" "j8" "j11" "k2" "k5" "k8" "k11" "l2" "l5" "l8" "l11"
[12,] "j3" "j6" "j9" "j12" "k3" "k6" "k9" "k12" "l3" "l6" "l9" "l12"

这是可行的,因为通过翻转维度,我们本质上构建了一个 3*12 矩阵的 4 元素数组,它对应于我们想要的行。然后我们使用 apply 来折叠额外的维度。

通用的matbinder(ma,n)函数看起来像

matbinder <- function(ma,n) {
d<-dim(ma)
r<-ceiling(d[3]/n)
a<-c(ma, rep(NA, (n*r-d[3]) * prod(d[1:2])))
dim(a)<-c(d[1], n*d[2],r)
apply(a,2,c)
}

关于arrays - 将矩阵并排放置以创建另一个矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24287889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com