R: matrix by vector multiplication

后端 未结 3 445
刺人心
刺人心 2020-12-06 16:10

I have following problem:

myvec <- c(1:3)

mymat <- as.matrix(cbind(a = 6:15, b = 16:25, c= 26:35))
mymat
       a  b  c
 [1,]  6 16 26
 [2,]  7 17 27         


        
相关标签:
3条回答
  • 2020-12-06 16:33

    An alternative, but longer way can be this one:

    rowSums(t(apply(mymat, 1, function(x) myvec*x)),na.rm=T)
    

    Is the only way that I found that can ignore NA's inside the matrix.

    0 讨论(0)
  • 2020-12-06 16:35

    The %*% operator in R does matrix multiplication:

    > mymat %*% myvec
          [,1]
     [1,]  116
     [2,]  122
     ...
    [10,]  170
    
    0 讨论(0)
  • 2020-12-06 16:50

    Matrices are vectors in column major order:

     colSums(  t(mymat) * myvec )  
    

    (Edited after hopefully reading question correctly this time.)

    0 讨论(0)
提交回复
热议问题