R:将2个矩阵按列乘以创建第三个矩阵 [英] R : Multiply 2 matrices column wise to create a third Matrix
问题描述
例如:
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
因此,我的新矩阵的第(1,1)个元素是M中第一列的总和乘以N中第一列的总和.
> M[,1] * N[,1]
[1] 20 42 66 92
> sum(M[,1] * N[,1])
[1] 220
我可以通过遍历l和n的所有可能值,使用2个For循环轻松创建这个新矩阵.但是,有没有更简单/更快的方法呢?
两个向量的元素乘积之和称为内部积.
矩阵乘法给出第一个矩阵中的行与第二个矩阵中的列的内积.要获取两个矩阵的列的内积,可以对第一个矩阵进行转置(将行转换为列),然后使用矩阵乘法获得所需的结果:
> t(M) %*% N
[,1] [,2]
[1,] 220 260
[2,] 564 668
[3,] 908 1076
[4,] 1252 1484
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?
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
这篇关于R:将2个矩阵按列乘以创建第三个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!