I'm trying to multiply each row of a matrix by the column of another matrix. For example:
mat1 <- matrix(rnorm(10), nrow=5, ncol=2)
mat2 <- matrix(rnorm(5), nrow=5)
I want to multiply each row of mat1 by mat2. The desired shape of the output is 5*2.
You could just use apply()
to multiply each column of mat1 by mat2. (The "*"
will carry out R's typically vectorized element-wise multiplication of the two equal-length vectors).
apply(mat1, 2, "*", mat2)
[,1] [,2]
[1,] 0.1785476 0.4175557
[2,] 0.2644247 -0.3745997
[3,] -0.5328542 0.8945527
[4,] -2.7351502 -0.7715341
[5,] -0.9719129 -0.1346929
Or better yet, convert mat1
to a vector to take advantage of R's recycling rules:
mat2 <- matrix(1:10, ncol=2)
mat1 <- matrix(1:5, ncol=1)
as.vector(mat1)*mat2
[,1] [,2]
[1,] 1 6
[2,] 4 14
[3,] 9 24
[4,] 16 36
[5,] 25 50
Your first matrix has five rows and two columns; your second matrix has five rows and one column. If they have the same number of rows and the second always has one column you can do
mat1 * rep(mat2,ncol(mat1))
[,1] [,2]
[1,] -0.2327958 0.76093047
[2,] -0.3636661 -0.18991299
[3,] -0.8729468 0.58214118
[4,] 0.8017349 -0.59781909
[5,] -0.2230380 -0.08296606
If mat1
actually had as many elements in its rows as mat2
had in its single column (as your words suggest) you would adjust this slightly
mat1 <- matrix(rnorm(10), nrow=2, ncol=5)
mat2 <- matrix(rnorm(5), nrow=5, ncol=1)
mat1 * rep(mat2,nrow(mat1))
[,1] [,2] [,3] [,4] [,5]
[1,] -0.19818805 -0.05938007 -1.7792597 0.06937307 -0.7193403
[2,] -0.05087793 0.10781853 0.2243285 -0.11416273 2.4063926
or in sarah's version
mat1 <- matrix(rnorm(10), nrow=5, ncol=2)
mat2 <- matrix(rnorm(2), nrow=2, ncol=1)
mat1 * rep(mat2,nrow(mat1))
[,1] [,2]
[1,] 0.1528393 0.68646359
[2,] 0.2420454 0.22987250
[3,] -0.2592124 -0.07626098
[4,] 0.4431273 0.27320838
[5,] -0.1698307 0.47578667
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With