Matrix multiplication in r

I am trying to multiply each row of a matrix by a column of another matrix. For instance:

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 output form is 5 * 2.

+4
source share
2 answers

You can simply use apply() to multiply each column mat1 by mat2 . ( "*" will perform R, as a rule, a vectorized phased multiplication of two vectors of equal length).

 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 vector to take advantage of the R disposal 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 
+5
source

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 only column (as your words suggest), you would slightly adjust this

 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 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 
+1
source

Source: https://habr.com/ru/post/1401702/


All Articles