[R] Multiple Vector with matrix in R

David Winsemius dwinsemius at comcast.net
Fri Nov 16 22:33:55 CET 2012


On Nov 16, 2012, at 8:34 AM, frespider wrote:

> Hi
> 
> Can someone show me an easy way to multiple a weighted vector with an
> matrix?
> 
> example below
> mat1<-matrix(sample(1:100,80,replace=TRUE),ncol=8)
> w <- 1/1:10
> 
> I want the first element in w to be multiplied by the first row of mat1 and
> 2nd element in w to be multiplied with the 2nd row and so on.
> 
> I have huge matrix is there an easy way other than diag(w)%*%mat1

Because of argument recycling, this would be the most simple way:

mat1 * w

> mat1 * w == diag(w) %*% mat1
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
 [1,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
 [2,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
 [3,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
 [4,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
 [5,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
 [6,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
 [7,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
 [8,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
 [9,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[10,] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE


--
David Winsemius, MD
Alameda, CA, USA




More information about the R-help mailing list