2014-06-18 177 views
2

我具有由下面的代碼給出的12點矩陣的陣列:並排把矩陣側創建另一個矩陣

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

讓它們被命名爲A,B,C ... ...你

我想創建一個矩陣,矩陣排列成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)。

+0

@Jilber:感謝編輯:使代碼更易讀。 – rnso

回答

2

我將以此作爲樣品基質,因爲它會在訂單中所有的字母,你喜歡

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元素數組與我們想要的行相對應的ces。然後我們使用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) 
} 
+0

太好了。這正是我想要的。謝謝。是否可以對其進行修改,使得如果ma中只有11個矩陣,則最終矩陣中的剩餘位置將填充「NA」。類似地,該函數可能用於命令matbinder(ma,5),因爲它目前會產生一個錯誤:dims [product 120]與對象[144]的長度不匹配。 – rnso

+0

@rnso我已經更新了我的答案,必要時用NA填充。 – MrFlick

+0

謝謝。這真是令人印象深刻。 – rnso

0

用我有限的知識,我設法下面的代碼:

matbinder2 = function(submat, mats_per_row){ 
    submat_dims = dim(submat) 
    submatr = submat_dims[1] 
    submatc = submat_dims[2] 
    submatn = submat_dims[3] 

    matc = submatc*mats_per_row 
    matr = submatr* ceiling(submatn/mats_per_row) 
    mat = array(NA, c(matr,matc)) 

    for(m in 1:submatn){ 
     r = 1+(floor(submatc*(m-1)/matc))*submatr 
     c = 1+((submatc*(m-1))%%matc) 
     i=1;j=1;k=0;l=0; 
     while(TRUE){ 
      mat[r+l,c+k] = submat[i,j,m] 
      j=j+1; k=k+1; 
      if(j>submatc){j=1;k=0; i=i+1;l=l+1;if(i>submatr){break;}} 
     } 
    } 
    mat 
}