# Add 2D Matrix to 3D Matrix

I have a 2D matrix that I need to add to a 3D matrix, for example:

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

Can we add this `mx2d`

to `mx3d`

to `mx3d.new`

become a `3x5x5`

matrix? Would it be easier if I convert the matrix to a list? Thank!

To be clear, based on what we have in `mx2d`

and `mx3d`

, I want to have something like:

```
> 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"
```

source to share

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

It works?

This gives me the following:

```
> 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"
```

source to share

I'm not sure if I understand your question correctly, but does

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

will provide you with what you want? Or, if you want to repeat it,

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

Perhaps if you can give some context for the problem you want to solve, I can be of more help.

Cheers, Jim

source to share