Rcpp函数始终返回零矩阵

pas*_*y51 1 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;
}
Run Code Online (Sandbox Code Playgroud)

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

jba*_*ums 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])

(表示例子)

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