Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: matrix by vector multiplication

Tags:

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

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

like image 514
jon Avatar asked Nov 08 '11 03:11

jon


People also ask

How do you multiply a matrix by a vector in R?

we can use sweep() method to multiply vectors to a matrix. sweep() function is used to apply the operation “+ or – or '*' or '/' ” to the row or column in the given matrix.

Can you multiply matrix with vector?

To define multiplication between a matrix A and a vector x (i.e., the matrix-vector product), we need to view the vector as a column matrix. We define the matrix-vector product only for the case when the number of columns in A equals the number of rows in x.

How do you multiply a matrix by 2 in R?

Data Visualization using R Programming To multiply two matrices by elements in R, we would need to use one of the matrices as vector. For example, if we have two matrices defined by names M1 and M2 then the multiplication of these matrices by elements can be done by using M1*as. vector(M2).

How do you make a matrix product in R?

Multiplication using %*% operator The Operator%*% is used for matrix multiplication satisfying the condition that the number of columns in the first matrix is equal to the number of rows in second. If matrix A[M, N] and matrix B[N, Z] are multiplied then the resultant matrix will of dimension M*N.


2 Answers

The %*% operator in R does matrix multiplication:

> mymat %*% myvec       [,1]  [1,]  116  [2,]  122  ... [10,]  170 
like image 185
Owen Avatar answered Oct 22 '22 21:10

Owen


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.

like image 44
Liliana Pacheco Avatar answered Oct 22 '22 22:10

Liliana Pacheco