简体   繁体   English

R:向量乘法矩阵

[英]R: matrix by vector multiplication

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,]  8 18 28
 [4,]  9 19 29
 [5,] 10 20 30
 [6,] 11 21 31
 [7,] 12 22 32
 [8,] 13 23 33
 [9,] 14 24 34
[10,] 15 25 35

I want to multiply the mymat with myvec and construct new vector such that 我想将mymat与myvec相乘并构造新的向量,使得

sum(6*1, 16*2, 26*3) 
sum(7*1, 17*2, 27*3)

....................
sum(15*1, 25*2, 35*3)

Sorry, this is simple question that I do not know... 抱歉,这是一个我不知道的简单问题...

Edit: typo corrected 编辑:错别字更正

The %*% operator in R does matrix multiplication: R中的%*%运算符会做矩阵乘法:

> mymat %*% myvec
      [,1]
 [1,]  116
 [2,]  122
 ...
[10,]  170

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. 是我发现可以忽略矩阵内NA的唯一方法。

Matrices are vectors in column major order: 矩阵是按列主要顺序排列的向量:

 colSums(  t(mymat) * myvec )  

(Edited after hopefully reading question correctly this time.) (希望这次正确阅读问题后进行了编辑。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM