forked from PacktPublishing/Learning-R-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrcpp-parallel.cpp
More file actions
28 lines (25 loc) · 782 Bytes
/
rcpp-parallel.cpp
File metadata and controls
28 lines (25 loc) · 782 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::depends(RcppParallel)]]
#include <Rcpp.h>
#include <RcppParallel.h>
using namespace Rcpp;
using namespace RcppParallel;
struct Transformer : public Worker {
const RMatrix<double> input;
RMatrix<double> output;
Transformer(const NumericMatrix input, NumericMatrix output)
: input(input), output(output) {}
void operator()(std::size_t begin, std::size_t end) {
std::transform(input.begin() + begin, input.begin() + end,
output.begin() + begin, [](double x) {
return 1 / (1 + x * x);
});
}
};
// [[Rcpp::export]]
NumericMatrix par_transform (NumericMatrix x) {
NumericMatrix output(x.nrow(), x.ncol());
Transformer transformer(x, output);
parallelFor(0, x.length(), transformer);
return output;
}