我编写了一个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)
规范参数将在调用函数时包含每列的规范.然而,输出始终是零矩阵.谁能告诉我这里出了什么问题?
| 归档时间: |
|
| 查看次数: |
189 次 |
| 最近记录: |