Sara U
Sara U

Reputation: 67

r multiplying each matrix row with elements from column

If these are the first 6 rows of my nx6 matrix

  x1    x2   x3  x4  x5  a1
   1    30    3  43   0  0.20
   3    40    2  35   0  0.21
   3    50    7  72   0  0.75
   4    40   58  63  10  0.55
   1    20   19  61  10  0.43
   4    20    5  49   0  0.62

The goal is to create a new nx5 matrix based on this logic. Each row from X1-X5 should be multiplied by the scalar values in a1 like this

a2
[1,30,3,43,0]*0.20 + [1,30,3,43,0]*0.21 + [1,30,3,43,0]*0.75 + [1,30,3,43,0]*0.55 + [1,30,3,43,0]*0.43 + [1,30,3,43,0]*0.62
                     [3,40,2,35,0]*0.21 + [3,40,2,35,0]*0.75 + [3,40,2,35,0]*0.55 + [3,40,2,35,0]*0.43 + [3,40,2,35,0]*0.62
                                          [3,50,7,72,0]*0.75 + [3,50,7,72,0]*0.55 + [3,50,7,72,0]*0.43 + [3,50,7,72,0]*0.62
                                                               [4,40,58,63,10]*0.55 + [4,40,58,63,10]*0.43 + [4,40,58,63,10]*0.62
                                                                          [1,20,19,61,10]*0.43 + [1,20,19,61,10]*0.62
                                                                                                         [4,20,5,49,0]*0.62

Finally resulting is a nx5 matrix below

 2.76     82.8   8.28    118.68    0
 7.68    102.4   5.12     89.6     0
 7.05    117.5  16.45    169.2     0
 6.4      64    92.8     100.8    16
 1.05     21    19.95     64.05   10.5
 2.48     12.4   3.1      30.38    0

Any pointers for accomplishing this appreciated. Thanks.

Upvotes: 1

Views: 75

Answers (1)

akrun
akrun

Reputation: 886938

We could loop over the sequence of rows with sapply, then do a the crossprod between the last column and the rest while we use the elements from that row to the last for the last column

t( sapply(seq_len(nrow(m1)), function(i) {
         x1 <-  m1[i:nrow(m1),6]
          x2 <- m1[i, -6]
          matrix(x2, length(x2), length(x1)) %*% x1 }))

data

m1 <- structure(c(1, 3, 3, 4, 1, 4, 30, 40, 50, 40, 20, 20, 3, 2, 7, 
58, 19, 5, 43, 35, 72, 63, 61, 49, 0, 0, 0, 10, 10, 0, 0.2, 0.21, 
0.75, 0.55, 0.43, 0.62), .Dim = c(6L, 6L), .Dimnames = list(NULL, 
    c("x1", "x2", "x3", "x4", "x5", "a1")))

Upvotes: 1

Related Questions