rmatrixvectorrcpprcpparmadillo

How can I pass in a row vector using Rcpparmadillo in R?


I'm writing a function using Rcpp for R where I want to perform vector cross products. So in R I am performing

t(v)%*%v

So I've written the following Rcpp function to do this

arma_code <-
    "arma::mat arma_vv(const arma::vec& v1, const arma::vec& v2) {
       return v1.t() * v2;
   };"
arma_vv = cppFunction(code = arma_code, depends = "RcppArmadillo")

This works fine, but I'd rather handle the transpose in R as there are situations where v1 has been transposed before input, so I tried the following instead

arma_code <-
    "arma::mat arma_vv(const arma::vec& v1, const arma::vec& v2) {
       return v1 * v2;
   };"
arma_vv = cppFunction(code = arma_code, depends = "RcppArmadillo")

but it seems to convert v1 to a column vector, even if I pass it through as a row vector, so I get an error

Error: matrix multiplication: incompatible matrix dimensions: 1000x1 and 1000x1

Solution

  • A few short minutes with the (generally excellent and accessible) Armadillo documentation would make it clear that for a conformant outer product you need a column vector (or arma::colvec) and a row vector (or arma::rowvec).

    RcppArmadillo supports both, but arma::vec is a shorthand for arma::colvec.

    > code <- "arma::mat vp(arma::colvec cv, arma::rowvec rv) { return cv * rv; }"
    > Rcpp::cppFunction(code, depends = "RcppArmadillo")
    > vp(as.numeric(1:4), as.numeric(1:4))
         [,1] [,2] [,3] [,4]
    [1,]    1    2    3    4
    [2,]    2    4    6    8
    [3,]    3    6    9   12
    [4,]    4    8   12   16
    >