简体   繁体   English

r矩阵逐元素乘积

[英]r matrix product element by element

I have 3 matrices: 我有3个矩阵:

 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) (注意,B [,i,drop = FALSE]%*%A [j ,, drop = FALSE]是(L by 1)矩阵与(1 by K_矩阵的乘积,因此是(L by K ),因为C是“和”,将结果矩阵的所有元素相加)

One way of doing this is creating a grid as expand.grid(1:n,1:m) and calculating D(.,.) for each of these elements. 一种实现方法是将网格创建为expand.grid(1:n,1:m)并为每个元素计算D(。,。)。 Any ideas of how to do it faster in R? 关于如何在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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