2

I'm a beginner with R. I wrote a double for loop for computing the dot product between each row of matrix x w.r.t. all the observations of sample X per time. I do not know how to store the results in a matrix having as columns the observations of sample X and as rows the rows of x. I hope someone can help me. Thanks in advance.

Here my code:

Dot.product <- function(x,X){
theta <- matrix(NA,nrow=nrow(x),ncol=nrow(X),byrow=T)
for(i in 1:nrow(X)){
for(j in 1:nrow(x)){
  theta[i,j] <- acos((sum(x[j,]*X[i,]))/(sqrt
        (sum(x[j,]*x[j,]))*sqrt(sum(t(X[i,])*X[i,]))))
 }}

return(theta)}
4

1 回答 1

2

你的尺寸不对。替换theta[i,j]theta[j,i]应该可以。

作为奖励,我将使用矢量化函数而不是双循环来编写您的函数:

Dot.product <- function(x, X) {
   a <- tcrossprod(x, X)
   n1 <- sqrt(rowSums(x * x))
   n2 <- sqrt(rowSums(X * X))
   acos(a / n1[row(a)] / n2[col(a)])
}

我已经检查过它们产生相同的结果。

于 2013-06-18T23:00:18.377 回答