RiskTech
RiskTech

Reputation: 1165

Matrix Column Multiplication in R

Given a 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

How can i return a new matrix which has all possible columns multiplications ?

The resulting Matrix would be :

          [,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]

Upvotes: 0

Views: 72

Answers (1)

Matthew Lundberg
Matthew Lundberg

Reputation: 42629

First, note the relationship between the columns that you want to multiply, and the result of a related combn result:

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

If the second row were decremented by 1, this is the set of columns that you want, and in the proper order. Now to use this to build the result:

> 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

Upvotes: 1

Related Questions