并排把矩阵侧创建另一个矩阵 [英] Putting matrices side by side to create another matrix
问题描述
我有按照code给出12矩阵数组:
I have an array of 12 matrices given by following code:
ma = array(sample(0:127,3*4*6,replace=TRUE), c(3,4,12))
让它们被命名为A,B,C ... L
Let they be named A,B,C...L
我要创建已高于矩阵排列在4rows矩阵* 3columns模式:
I want to create a matrix which has above matrices arranged in a 4rows*3columns pattern:
ABC
DEF
GHI
JKL
所以最终矩阵将具有12rows和12列。
So final matrix will have 12rows and 12 columns.
我可以做到这一点下面code:
I can do this following code:
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]))
但我不能写一个通用的功能是:
But I am not able to write a generic function for this:
matbinder(MA,N)#其中MA是输入矩阵阵列和n是放在初始矩阵的数量在一排(3在这种情况下)。
matbinder(ma,n) # where ma is input matrix array and n is number of initial matrices to be put in one row (3 in this case).
推荐答案
我将以此作为样品基体,因为它会在你的命令所有的信件像
I'll use this as a sample matrix since it will have all the letters in the order you like
ma = array(as.vector(t(outer(letters[1:12],1:12, FUN=paste0))), c(3,4,12))
然后,你可以做这样的转变
Then you can do the transformation like
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元素的数组。然后,我们使用申请跨额外的维度崩溃。
This works because by flipping the dimensions, we essentially build a 4 element array of 3*12 matrices which correspond to the rows we want. Then we use apply to collapse across the extra dimension.
一个普通的 matbinder(MA,N)
函数看起来像
A generic matbinder(ma,n)
function would look like
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)
}
这篇关于并排把矩阵侧创建另一个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!