Da Kyoung Lee
Da Kyoung Lee

Reputation: 11

Get matrix/vector type from C using Rcpp

I am trying to get some results by using Rcpp and this is the code.

#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;
}

In fact there are some more functions and the file name of this code is "test.cpp" And I called this file in R by using

sourceCpp("test.cpp")

There was no error and I could use the function "compssr" the first function(return type: double) But I couldn't call the function Scaling_X

Is there any error in my code? I made other functions and I could use the function with return type double, but I couldn't use others(NumericMatrix, NumericVector, List)

Upvotes: 0

Views: 90

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368509

You are missing the

// [[Rcpp::export]]

in front of function Scaling_X so the compileAttributes() function does as it has been told: compile both functions, make just one available.

Upvotes: 5

Related Questions