arrays - Putting matrices side by side to create another matrix -
i have array of 12 matrices given next code:
ma = array(sample(0:127,3*4*6,replace=true), c(3,4,12)) let named a,b,c...l
i want create matrix has above matrices arranged in 4rows*3columns pattern:
abc def ghi jkl so final matrix have 12rows , 12 columns.
i can next 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 not able write generic function this:
matbinder(ma,n) # ma input matrix array , n number of initial matrices set in 1 row (3 in case).
i'll utilize sample matrix since have letters in order like
ma = array(as.vector(t(outer(letters[1:12],1:12, fun=paste0))), c(3,4,12)) then can transformation like
a<-ma dim(a) <- c(3,12,4) apply(a,2,c) which produces
[,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" this works because flipping dimensions, build 4 element array of 3*12 matrices correspond rows want. utilize apply collapse across dimension.
a generic matbinder(ma,n) function 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) } arrays r matrix
No comments:
Post a Comment