R:将2个矩阵按列乘以创建第三个矩阵 [英] R : Multiply 2 matrices column wise to create a third Matrix

查看:131
本文介绍了R:将2个矩阵按列乘以创建第三个矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个矩阵,分别说M和N的大小分别为m×n和m×l.我想创建一个大小为n的第三个矩阵,以使新矩阵的第(i,j)个条目是通过将M的第i列与N的第j列相乘而获得的矢量的总和

例如:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆