Samuel Shamiri
Samuel Shamiri

Reputation: 137

Row matrix minus vector with Rcpp

I am mainly R user, but I would like to learn Rcpp to improve my coding(speed). So I start out playing around with C++ and Rcpp, I thought I’d just try to write the following simple function which takes the row of matrix, (i.e first row) and deduct a vector from it (m[1,]-vec).

I know this sound silly and simple but I am not able to get it work.

code <- '
arma::mat beta = Rcpp::as(beta_);
arma::vec y = Rcpp::as(y_);
arma::rowvec S= beta.row(0);

arma::vec d = S - y;
return Rcpp::wrap(d);
'
fun <- cxxfunction(signature(beta_ ="matrix",y_="numeric"),code, plugin="RcppArmadillo")
m <- matrix(1:9,3)
vec <- c(1,2,5)
fun(m,vec)
Error in fun(m, vec) :

in R this wil be done as,
m[1,]-vec
0 2 2

Upvotes: 1

Views: 1448

Answers (1)

baptiste
baptiste

Reputation: 77096

library(RcppArmadillo)
library(inline)
code <- '
arma::mat beta = Rcpp::as<arma::mat>(beta_);
arma::rowvec y = Rcpp::as<arma::rowvec>(y_);
arma::rowvec S= beta.row(0);
arma::rowvec d = S - y;
return Rcpp::wrap(d);
'
fun <- cxxfunction(signature(beta_ ="matrix",y_="numeric"),code, plugin="RcppArmadillo")
m <- matrix(1:9,3)
vec <- c(1,2,5)
fun(m,vec)

Upvotes: 3

Related Questions