Skip to content

Instantly share code, notes, and snippets.

@helmingstay
Last active November 29, 2016 10:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helmingstay/17d5d9f241c4170a29d1681db0111065 to your computer and use it in GitHub Desktop.
Save helmingstay/17d5d9f241c4170a29d1681db0111065 to your computer and use it in GitHub Desktop.
Example of R Reference Classes + Rcpp Attributes
#include <Rcpp.h>
using Rcpp::NumericVector;
// [[Rcpp::export]]
void convolveCpp(const NumericVector a, const NumericVector b, NumericVector xab) {
int na = a.size(), nb = b.size();
if ( (na + nb-1) != xab.size() ) {
Rcpp::Rcout << "ab.size: " << na+nb << ", xab.size: " << xab.size() << std::endl;
Rcpp::stop("Dimension mismatch in convolveCpp");
};
// zero-out
xab.fill(0);
// convolve
for (int i = 0; i < na; i++) {
for (int j = 0; j < nb; j++) {
xab[i + j] += a[i] * b[j];
}
}
}
library(Rcpp)
sourceCpp('convolve.cpp')
Convolver <- setRefClass("Convolver",
fields = list(
data = "numeric",
answer = "numeric"
),
methods = list(
convolve = function(x) {
dim_new <- length(x)+length(data)-1
## only re-alloc if necessary
if (length(answer) != dim_new) {
cat('## Realloc answer\n')
answer <<- numeric(dim_new)
}
convolveCpp(data, x, answer)
cat(c('Answer: ', round(answer,3), '\n'))
}
)
)
kernel1 <- c(1,3,1)/5
kernel2 <- c(2,1,2)/5
dat <- c(1:5, 0, 5:1)
the_test <- Convolver$new(data=dat/sum(dat))
the_test$convolve(kernel1)
the_test$convolve(kernel2)
@helmingstay
Copy link
Author

helmingstay commented Nov 29, 2016

In R, run with:

source("Convolver.cpp")

@sgsokol
Copy link

sgsokol commented Nov 29, 2016

source("Convolver.R")
(not ".cpp")?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment