【问题标题】:Get matrix/vector type from C using Rcpp使用 Rcpp 从 C 中获取矩阵/向量类型
【发布时间】:2018-07-21 15:13:04
【问题描述】:

我正在尝试使用 Rcpp 获得一些结果,这是代码。

#include <Rcpp.h>
#include <math.h>
using namespace Rcpp;
enter code here

// [[Rcpp::export]]
double compssr(NumericMatrix dist, NumericVector x, int n, int p) {
    double ssr = 0; double del_sq = 0; double del_ij = 0;
    int i, j, ip;
    for (i = 0; i < n; i++) {
        for (j = 0; j < i; j++) {
            for (ip = 0; ip < p; ip++) {
                del_sq = del_sq + (x(i, ip) - x(j, ip))*(x(i, ip) - x(j, ip));
                if (i == j) del_sq = 0;
            }
            del_ij = sqrt(del_sq);
            ssr = ssr + (dist(i, j) - del_ij)*(dist(i, j) - del_ij);
        }}
    return ssr;
}

NumericMatrix Scaling_X(NumericVector xbar, NumericMatrix x, double n, double p) {

    NumericMatrix Sig_x(p, p);
    int i, ii, ip, ip2;

    for (ii = 0; ii < n; ii++) {
        for (i = 0; i < p; i++) {
            x(ii, i) = x(ii, i) - xbar(i);
        }}

    for (i = 0; i < n; i++) {
        for (ip = 0; ip < p; ip++) {
            for (ip2 = 0; ip2 < p; ip2++) {
                Sig_x(ip, ip2) = Sig_x(ip, ip2) + x(i, ip)*x(i, ip2);
            }}}

    for (i = 0; i < Sig_x.ncol(); i++) {
        for (ii = 0; ii < Sig_x.nrow(); ii++) {
            Sig_x(i, ii) = Sig_x(i, ii) / n;
        }}
    return Sig_x;
}

其实还有一些函数,这段代码的文件名为“test.cpp” 我使用 R 在 R 中调用了这个文件

sourceCpp("test.cpp")

没有错误,我可以使用函数“compssr”第一个函数(返回类型:double) 但我无法调用函数 Scaling_X

我的代码有错误吗? 我做了其他函数,我可以使用返回类型为 double 的函数,但我不能使用其他函数(NumericMatrix,NumericVector,List)

【问题讨论】:

  • 脚本中有enter code here吗?

标签: r rcpp


【解决方案1】:

你错过了

// [[Rcpp::export]]

在函数Scaling_X 前面,所以compileAttributes() 函数按照它的要求执行:编译这两个函数,只使一个可用。

【讨论】:

  • 天哪.. 现在可以了。非常感谢。我应该早点在这里问。
  • 好!欢迎来到 StackOverflow。由于这里很常见,请考虑 a) 通过单击向上三角形来支持答案和/或 b) 通过单击作为问题的原始发布者的“标记”来接受答案。
猜你喜欢
  • 2014-12-29
  • 2012-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
相关资源
最近更新 更多