将矩阵连接成数组 [英] joining matrices into an array
问题描述
我有几种矩阵,希望将它们按如下方式加入到数组中:
I have several matrices that i would like to join them into an array as follows:
> 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))
我可能做错了什么?
推荐答案
更新:
从注释中看来,所需要做的只是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
组合在一起是很有意义的:
I suppose that if you have a lot of these, it would make sense to arrange for them to held in a list and then use do.call
to cbind
them together:
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
连接为单个向量,然后将其与相应的dim
传递给array
争论.例如
Original
It isn't really very clear how you want the matrices to be arrange in the array. If you mean to stack the matrices like a pile of papers, with each leaf of paper a matrix, then we can simply concatenate the matrices into a single vector with c
and then pass that to array
with an appropriate dim
argument. 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
这篇关于将矩阵连接成数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!