Palace Chan
Palace Chan

Reputation: 9203

What is a good way to carry out a row-wise dot product between a pair of matrices in R?

I have an NxK matrix x and another matrix of identical dimensions which contains coefficients for each of the K features and each of N groups. I would like a K vector where the i-th entry is the dot product of the i-th row in x with the i-th row of the coefficient matrix. For example if x is:

x = matrix(rep(1:3,each=2),ncol=2,byrow=TRUE)

and the coeff matrix is:

coeff = matrix(c(.5,1,0),nrow=3,ncol=2)

The result should be the vector (1,4,0) because the dot product of (1,1) and (.5,.5) is 1, the dot product of (2,2) and (1,1) is 4 and the dot product of (3,3) with (0,0) is 0. I can imagine doing this with a call to sapply on the indices where each iteration is a dot product, but am wondering if there is a better way using a built-in function like sweep or friends..

Upvotes: 4

Views: 1562

Answers (1)

akuiper
akuiper

Reputation: 215067

Multiply the two matrix using * and then do rowSums:

rowSums(x * coeff)
[1] 1 4 0

Upvotes: 6

Related Questions