2012-03-25 144 views
3

我有一個二維矩陣,我需要添加到一個3D矩陣,例如:添加二維矩陣轉換成3D矩陣

mx3d <- array(1:60, c(3,4,5)) 
mx2d <- array(letters[1:15], c(3,5)) 

是否有可能加入到mx3d所以這mx2dmx3d.new成爲3x5x5矩陣?如果我將矩陣轉換爲列表,會更容易嗎?謝謝!

要清楚的基礎上,我們所擁有的mx2dmx3d,我想有這樣的:

> mx3d.new 
, , 1 

    [,1] [,2] [,3] [,4] [,5] 
[1,] 1 4 7 10 "a" 
[2,] 2 5 8 11 "b" 
[3,] 3 6 9 12 "c" 

, , 2 

    [,1] [,2] [,3] [,4] [,5] 
[1,] 13 16 19 22 "d" 
[2,] 14 17 20 23 "e" 
[3,] 15 18 21 24 "f" 

, , 3 

    [,1] [,2] [,3] [,4] [,5] 
[1,] 25 28 31 34 "g" 
[2,] 26 29 32 35 "h" 
[3,] 27 30 33 36 "i" 

, , 4 

    [,1] [,2] [,3] [,4] [,5] 
[1,] 37 40 43 46 "j" 
[2,] 38 41 44 47 "k" 
[3,] 39 42 45 48 "l" 

, , 5 

    [,1] [,2] [,3] [,4] [,5] 
[1,] 49 52 55 58 "m" 
[2,] 50 53 56 59 "n" 
[3,] 51 54 57 60 "o" 
+0

你是什麼 「加入到」 是什麼意思?如果您指的是矩陣加法,那麼矩陣加法僅針對相同大小的矩陣定義。 – 2012-03-25 05:35:17

+0

請參閱最新的問題。謝謝! – Rock 2012-03-25 05:55:46

回答

6
library(abind) 
mx3d.new <- abind(mx3d, mx2d, along= 2) 
for(i in 1:5) print(mx3d.new[,,i]) 

運作的?

它給了我這樣的:

> for(i in 1:5) print(mx3d.new[,,i]) 

    [,1] [,2] [,3] [,4] [,5] 

[1,] "1" "4" "7" "10" "a" 

[2,] "2" "5" "8" "11" "b" 

[3,] "3" "6" "9" "12" "c" 

    [,1] [,2] [,3] [,4] [,5] 

[1,] "13" "16" "19" "22" "d" 

[2,] "14" "17" "20" "23" "e" 

[3,] "15" "18" "21" "24" "f" 

    [,1] [,2] [,3] [,4] [,5] 

[1,] "25" "28" "31" "34" "g" 

[2,] "26" "29" "32" "35" "h" 

[3,] "27" "30" "33" "36" "i" 

    [,1] [,2] [,3] [,4] [,5] 

[1,] "37" "40" "43" "46" "j" 

[2,] "38" "41" "44" "47" "k" 

[3,] "39" "42" "45" "48" "l" 

    [,1] [,2] [,3] [,4] [,5] 
[1,] "49" "52" "55" "58" "m" 

[2,] "50" "53" "56" "59" "n" 

[3,] "51" "54" "57" "60" "o" 
+0

謝謝吉姆。我必須說這很酷!從來不知道'abind'。謝謝! – Rock 2012-03-25 06:19:08

2

我不知道我正確理解你的問題,但確實

mx3d.new <- array(letters[1:75],c(3,5,5)) 

給你你想要的?或者如果你想重複它,

mx3d.new <- array(letters[1:15],c(3,5,5)) 

也許如果你給一些你想解決的問題的上下文,我可以給予更多的幫助。

乾杯, 吉姆

+0

我在這個問題上添加了更多描述。希望它解釋自己。 – Rock 2012-03-25 05:56:54