Rcpp函数始终返回零矩阵

时间:2015-01-13 01:24:27

标签: r rcpp

我编写了一个Rcpp函数来计算矩阵列之间的余弦相似度:

#include <Rcpp.h>
using namespace Rcpp;

// Below is a simple example of exporting a C++ function to R. You can
// source this function into an R session using the Rcpp::sourceCpp 
// function (or via the Source button on the editor toolbar)

// For more on using Rcpp click the Help button on the editor toolbar

// [[Rcpp::export]]
NumericMatrix mysimil(NumericMatrix X, NumericVector norms) {
  int nrow = X.nrow(), ncol = X.ncol();
  NumericMatrix out(nrow, ncol);

  for (int i = 0; i < nrow; i++) {
    for (int j = i+1; j < ncol; j++) {
      out(i,j) <- sum(X(_,i)*X(_,j))/(norms[i]*norms[j]);
      out(j,i) <- out(i,j);
    }
  }
  return out;
}

规范参数将在调用函数时包含每列的规范。然而,输出始终是零矩阵。有人能告诉我这里出了什么问题吗?

1 个答案:

答案 0 :(得分:7)

编译代码时sourceCpp返回的警告(即warning: value computed is not used [-Wunused-value])表明分配存在问题。

实际上,在为out分配值时,您使用的是R赋值运算符<-,而不是C / C ++运算符=。您的<-仍然是有效的C ++代码,被视为不等式(x <- y等同于x < -y)。在这种情况下,您的表达式会询问:

out(i,j)小于-sum(X(_,i) * X(_,j)) / (norms[i]*norms[j])

(ideone example)

更正操作符并正确分配值。

相关问题