Xia.Song
Xia.Song

Reputation: 426

How to build a constant matrix in Rcpp?

I'm a Rcpp user, in my cpp file, I need to use a matrix repeatedly. I want to define a constant matrix, but I don't know how to do it.

I used to defined a single constant double type variable in Rcpp and it works well for me. But when I repeat the same way for a matrix,

#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>
// [[Rcpp::depends(RcppArmadillo)]]

const int a[3][4] = {  
  {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
  {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
  {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};

// [[Rcpp::export]]
double tf(arma::mat x){
  double aa=arma::sum(x+a);
  return(aa);
}

it has the following error

enter image description here

Upvotes: 0

Views: 238

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368181

You missed the existing examples at the (excellent, really) Armadillo documentation.

You missed that sum() on a matrix returns a vector.

You also missed the (required) use of as_scalar when assigning to a scalar.

A modified and repaired version of your code follows, along with the output.

Code

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]

// -- for { } init below
// [[Rcpp::plugins(cpp11)]]

// [[Rcpp::export]]
arma::mat getMatrix() {
  const arma::mat a = { {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
                        {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
                        {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
  };
  return a;
}

// [[Rcpp::export]]
double tf(arma::mat x){
  double aa = arma::as_scalar(arma::sum(arma::sum(x+x)));
  return(aa);
}

/*** R
tf( getMatrix() )
*/

Output

R> Rcpp::sourceCpp("~/git/stackoverflow/57105625/answer.cpp")

R> tf( getMatrix() )
[1] 132
R> 

Upvotes: 5

Related Questions