Skip to content


How to (efficiently) multiply all rows of a matrix by a vector in R

If you’re reading this, you most likely know that using for() loops isn’t an efficient way to do a high amount of computations in R. Vectorizing the code is a must if you want to get the best possible performances.

So, to multiply all rows of a matrix by a vector, we’ll first look at how to multiply all columns by a vector. Straight to the code:
A=matrix(1,3,3);
b=c(1,2,3);
A*b;

That’s right, the ‘*’ operator just does that when used on a matrix and a vector. So a first obvious solution is to transpose the matrix, do the multiplication, and then transpose it back:
A=matrix(1,3,3);
b=c(1,2,3);
t(t(A)*b);

And that’s it already.

Still, you may be interested to know that R also features the sweep() function, which can also be used to do that, and more. It’s not needed in this case, but maybe for more complex situation you’ll find it handy. The code would be:
A=matrix(1,3,3);
b=c(1,2,3);
sweep(A,2,b,'*');

The first argument is the matrix, the second is 2 for row and 1 for column, the third is the vector, and the last is the operator you want to apply. This might work with functions too, like apply(), although I didn’t check that.

Posted in programming, R (R-project).


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.

Sorry about the CAPTCHA that requires JS. If you really don't want to enable JS and still want to comment, you can send me your comment via e-mail and I'll post it for you.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA