简体   繁体   中英

r matrix product element by element

I have 3 matrices:

 A (n by K), 

 B (L by m) and 

 C (L by K) 

and would like to produce a 4th matrix

D (n by m) 

with elements

D(i,j) = sum(B[,i,drop=FALSE]%*%A[j,,drop=FALSE] * C)

(Notice that B[,i,drop=FALSE]%*%A[j,,drop=FALSE] is the product of a (L by 1) matrix with a (1 by K_ matrix, and hence is (L by K), as C is. "sum" sums all elements of the resulting matrix)

One way of doing this is creating a grid as expand.grid(1:n,1:m) and calculating D(.,.) for each of these elements. Any ideas of how to do it faster in R?

Thanks!

library(reshape2)
library(plyr)  
m <- 100;n <- 100;K <- 100;L <- 100
A <- matrix(sample(1:n),nrow=n,ncol=K)
B <- matrix(sample(1:L),nrow=L,ncol=m)
C <- matrix(sample(1:L),nrow=L,ncol=K)

h <- ddply(expand.grid(1:m,1:n),.(Var1,Var2),
           f <- function(i) {sum(B[,i$Var1,drop=FALSE]%*%A[i$Var2,,drop=FALSE]*C)})
D <- acast(h, Var2 ~ Var1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM