0
votes

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

1 Answers

3
votes

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