2012-03-15 211 views
4

我試圖將矩陣的每一行乘以另一個矩陣的列。例如:r中的矩陣乘法

mat1 <- matrix(rnorm(10), nrow=5, ncol=2) 
mat2 <- matrix(rnorm(5), nrow=5) 

我想通過mat2乘以mat1的每一行。所需的輸出形狀是5 * 2。

+3

如果你想[矩陣乘法(http://en.wikipedia.org/wiki/Matrix_multiplication),爲TH e標題表明,即想要將第一矩陣的行乘以第二列的列,這是'mat1%*%mat2'。但是這需要第一個矩陣具有與第二個矩陣一樣多的列 - 在您的示例中不是這種情況。 – 2012-03-15 23:39:54

回答

5

你可以只使用apply()通過MAT2繁殖MAT1的每一列。 ("*"將執行R的典型矢量化兩個等長向量的元素方式乘法)。

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 

或者更好的是,轉換mat1爲載體,採取討論R的回收規則的優勢:

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 
1

你的第一個矩陣有五個行兩列;你的第二個矩陣有五行一列。如果他們有相同的行數和第二總有一列,你可以做

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 

如果mat1竟然出現在其行如mat2曾在其單列爲許多元素(如你的話建議),你會調整這種略帶

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 

或在薩拉的版本

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