R : Multiply 2 matrices column wise to create a third Matrix

怎甘沉沦 提交于 2020-01-06 14:39:12

问题


I have 2 matrices, say M and N of sizes m by n and m by l respectively. I would like to create a third matrix of size l by n such that the (i,j)th entry of the new matrix is the sum of the vector obtained by multiplying i'th column of M with the j'th column of N.

For eg:

M = matrix(1:16, 4,4)
> M
     [,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    2    6   10   14
[3,]    3    7   11   15
[4,]    4    8   12   16

N = matrix(20:27,4,2)
> N
     [,1] [,2]
[1,]   20   24
[2,]   21   25
[3,]   22   26
[4,]   23   27

So, the (1,1)th element of my new matrix is the sum of the first column in M times the first column in N. In this case

> M[,1] * N[,1]
[1] 20 42 66 92
> sum(M[,1] * N[,1])
[1] 220 

I can create this new matrix easily using 2 For Loops by iterating over all possible values of l and n. But is there a simpler/faster way of doing this?


回答1:


The sum of the element-wise product of two vectors is called an inner product.

Matrix multiplication gives the inner product of rows in the first matrix with columns in the second. To get the inner products of columns of two matrices, you can transpose the first matrix (converting rows to columns) then use matrix multiplications to get the desired results:

> t(M) %*% N
     [,1] [,2]
[1,]  220  260
[2,]  564  668
[3,]  908 1076
[4,] 1252 1484


来源:https://stackoverflow.com/questions/22278885/r-multiply-2-matrices-column-wise-to-create-a-third-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!