将矩阵连接成一个数组

时间:2013-04-03 05:28:40

标签: r matrix

我有几个矩阵,我想将它们加入到一个数组中,如下所示:

> mat1
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

> mat2
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

> mat3
     [,1] [,2] [,3]
[1,]   13   15   17
[2,]   14   16   18

我试过这个:

dime=dim(mat1)
Array=array(mat1, mat2,mat3,dim(dime))

出现以下错误:

Error in array(mat1, mat2, mat3, dim(dime)) : 
  unused argument(s) (dim(dime))

我可能做错了什么?

1 个答案:

答案 0 :(得分:2)

更新

从评论看来,所需要的只是cbind三个矩阵:

> cbind(mat1, mat2, mat3)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    1    3    5    1    3    5    1    3    5
[2,]    2    4    6    2    4    6    2    4    6

我想如果你有很多这些,那么安排将它们保存在列表中然后将do.call cbind放在一起是有意义的:

mlist <- list(mat1, mat2, mat3) ## simulate matrices stored as a list

## cbind them via a `do.call` call
do.call(cbind, mlist)

产生

> do.call(cbind, mlist)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    1    3    5    1    3    5    1    3    5
[2,]    2    4    6    2    4    6    2    4    6

原始

您希望如何在阵列中排列矩阵并不是很清楚。如果你的意思是像一堆纸一样堆叠矩阵,每张纸都是矩阵,那么我们可以简单地将矩阵连接到一个带有c的矢量中,然后将其传递给array适当的dim参数。 E.g。

> mat1 <- mat2 <- mat3 <- matrix(1:6, ncol = 3)
> array(c(mat1, mat2, mat3), dim = c(2,3,3))
, , 1

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

, , 2

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

, , 3

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