Rcpp函数始终返回零矩阵

Rcpp函数始终返回零矩阵,r,rcpp,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 butt

我编写了一个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;
}
在调用函数时,norms参数将包含每列的规范。然而,输出总是零矩阵。有人能告诉我这里出了什么问题吗?

sourceCpp在编译代码时返回的警告,即警告:未使用计算值[-Wunused value],表明赋值有问题

实际上,当将值分配给out时,您使用的是R赋值运算符,sourceCpp在编译代码时返回的警告,即警告:未使用计算值[-Wunused value],表明赋值存在问题


事实上,当给out赋值时,您使用的是R赋值运算符,为什么会偏离主题呢?这是一个完全正确的Rcpp问题,尽管有一个新的新手错误。我过去也犯过同样的错误@哈德利:很高兴听到我不是一个人!为什么这会偏离主题?这是一个完全正确的Rcpp问题,尽管有一个新的新手错误。我过去也犯过同样的错误@哈德利:很高兴听到我不是一个人!哦非常感谢你。复制粘贴的危险!我现在想知道为什么这不会产生错误?是@passerby51-谢谢。那很有趣。哦。。。非常感谢你。复制粘贴的危险!我现在想知道为什么这不会产生错误?是@passerby51-谢谢。这很有趣。