R中的矩阵列乘法

时间:2014-07-14 19:40:29

标签: r matrix

给出一个矩阵:

bb=replicate(3, rnorm(3))

           [,1]       [,2]       [,3]
[1,]  0.5556358  1.6611142  0.2374830
[2,] -0.6672456 -0.5038430  0.9814712
[3,] -0.1391022 -1.2072500 -0.6219965

如何返回一个包含所有可能列乘法的新矩阵?

结果矩阵将是:

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

1 个答案:

答案 0 :(得分:1)

首先,请注意要与之相乘的列之间的关系,以及相关combn结果的结果:

combn(4,2)
##     [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]    1    1    1    2    2    3
## [2,]    2    3    4    3    4    4

如果第二行减1,则这是您想要的列集,并且顺序正确。现在用它来构建结果:

> x <- matrix(1:9,3,3)
> x
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
> apply(combn(ncol(x)+1, 2), 2, function(i) x[,i[1]] * x[,i[2]-1])
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    4    7   16   28   49
[2,]    4   10   16   25   40   64
[3,]    9   18   27   36   54   81