Return a Matrix that has all possible column multiplications of another Matrix (R)

2

Be 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 second array with all possible column multiplications?

The resulting array would be:

          [,1]         [,2]         [,3]          [,4]          [,5]          [,6]          [,7]          [,8]          [,9]                  
[1,]  [1,1]*[1,1]  [1,1]*[1,2]  [1,1]*[1,3]   [1,1]*[1,2]   [1,2]*[1,2]   [1,3]*[1,2]   [1,1]*[1,3]   [1,2]*[1,3]   [1,3]*[1,3]           
[2,]  [2,1]*[2,1]  [2,1]*[2,2]  [2,1]*[2,3]   [2,1]*[2,2]   [2,2]*[2,2]   [2,3]*[2,2]   [2,1]*[2,3]   [2,2]*[2,3]   [2,3]*[2,3]   
[3,]  [3,1]*[3,1]  [3,1]*[3,2]  [3,1]*[3,3]   [3,1]*[3,2]   [3,2]*[3,2]   [3,3]*[3,2]   [3,1]*[3,3]   [3,2]*[3,3]   [3,3]*[3,3] 
    
asked by anonymous 17.07.2014 / 14:43

1 answer

1

If you get it right, you want all combinations of element-by-element multiplication of columns 1 to 3, resulting in 9 combinations (three of them redundant) ie: (1,1), (1,2), (1 , 3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3).

If so, one way is to create the index combinations and then use apply to perform the multiplications:

indices <- merge(1:ncol(bb), 1:ncol(bb))
results <- apply(indices, 1, function(i) bb[,i[1]]*bb[,i[2]])

Or you can do directly using lapply combined with sapply :

 results <- lapply(1:3, function(i) sapply(1:3, function(j){bb[,i] * bb[,j]}))
 results <- do.call("cbind", results)

The last do.call is to rebuild the array.

Result (same in both cases):

 results   
                [,1]        [,2]       [,3]        [,4]        [,5]       [,6]       [,7]
    [1,] 0.987438763  0.09896978 -1.4313778  0.09896978 0.009919619 -0.1434652 -1.4313778
    [2,] 0.001977491 -0.01836587 -0.0155266 -0.01836587 0.170572190  0.1442026 -0.0155266
    [3,] 0.297173072 -0.57771732  0.5811062 -0.57771732 1.123107495 -1.1296955  0.5811062
               [,8]      [,9]
    [1,] -0.1434652 2.0749057
    [2,]  0.1442026 0.1219096
    [3,] -1.1296955 1.1363222
    
18.07.2014 / 00:41