celestialgod

bsxfun in R by Rcpp

Apr 23rd, 2015
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 0.73 KB | None | 0 0
  1. library(Rcpp)
  2. sourceCpp(code = '
  3. #include <RcppArmadillo.h>
  4. // [[Rcpp::depends(RcppArmadillo)]]
  5. using namespace Rcpp;
  6. using namespace arma;
  7.  
  8. // [[Rcpp::export]]
  9. NumericMatrix bsxfun_Rcpp(Function f, mat A, mat B){
  10.  uword Nrow = (A.n_rows > B.n_rows)? A.n_rows : B.n_rows,
  11.        Ncol = (A.n_cols > B.n_cols)? A.n_cols : B.n_cols;
  12.  return as<NumericMatrix>( f(
  13.    as<NumericMatrix>( wrap(repmat(A, Nrow / A.n_rows, Ncol / A.n_cols))),
  14.    as<NumericMatrix>( wrap(repmat(B, Nrow / B.n_rows, Ncol / B.n_cols)))
  15.  ));
  16. }')
  17. A = matrix(rnorm(4), 4, 1)
  18. B = matrix(rnorm(8), 4, 2)
  19. bsxfun_Rcpp(function(x, y) x + y, B, A)
  20. sweep(B, 1, A, '+')
  21.  
  22. bsxfun_Rcpp(pmin, B, A)
  23. sweep(B, 1, A, pmin)
  24.  
  25. bsxfun_Rcpp(pmax, B, A)
  26. sweep(B, 1, A, pmax)
Advertisement
Add Comment
Please, Sign In to add comment