基于矩阵和向量创建数组

时间:2014-02-19 01:37:31

标签: r

我有一个名为A的矩阵:

A=matrix(c(1,2,3,4),nrow=2,ncol=2)

然后我想以下列方式获取一个基于矢量的数组,比如说a=c(1,0.5,2)

1A =矩阵(C(1,2,3,4),nrow = 2,NcoI位= 2)

0.5A =矩阵(C(0.5,1,1.5,2),nrow = 2,NcoI位= 2)

2A =矩阵(C(2,4,6,8),nrow = 2,NcoI位= 2)

所以我希望矩阵1A在数组的第一维中,0.5A在数组的第二维中,最后2A在数组的第三维中。

感谢。

1 个答案:

答案 0 :(得分:0)

使用simplify = 'array'sapply

sapply(c(1,0.5,2),'*',A,simplify='array')
# , , 1
# 
#      [,1] [,2]
# [1,]    1    3
# [2,]    2    4
# 
# , , 2
# 
#      [,1] [,2]
# [1,]  0.5  1.5
# [2,]  1.0  2.0
# 
# , , 3
# 
#      [,1] [,2]
# [1,]    2    6
# [2,]    4    8

kronecker获取两个阵列的kronecker产品

kronecker(array(c(1,0.5,2),c(1,1,3)),A)
# , , 1
# 
#      [,1] [,2]
# [1,]    1    3
# [2,]    2    4
# 
# , , 2
# 
#      [,1] [,2]
# [1,]  0.5  1.5
# [2,]  1.0  2.0
# 
# , , 3
# 
#      [,1] [,2]
# [1,]    2    6
# [2,]    4    8