Search code examples
rcpprcpparmadillo

Fail to call ones or eye function when using RcppArmadillo


I want to use one or eye function in Armadillo to construct matrices or vectors. However, it does not allow me to do so. Here is a sample code:

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
// [[Rcpp::export]]
SEXP Generate(arma::mat Mat){
arma::mat Mat_2 = ones<mat>(5,6);
}

error message reminds me of use of undeclared idenfier of 'mat'. When I remove <mat>, another massage says use of undeclared idenfier of 'ones'.

I looked up the Armadillo tutorial which includes the ones function. I wonder why my code fails to call it. Did I miss something?


Solution

  • There are a few problems in your code:

    • Why return SEXP? Use types to your advantage
    • Why pass Mat in if you do not use it?
    • No return statement
    • Somewhat loose use of namespaces.

    A cleaned up version follows:

    #include <RcppArmadillo.h>
    
    // [[Rcpp::depends(RcppArmadillo)]]
    
    // [[Rcpp::export]]
    arma::mat Generate(int n=5, int k=6){
        arma::mat m = arma::ones<arma::mat>(n,k);
        return m;
    }
    
    /*** R
    Generate()
    */
    

    It compiles and runs fine:

    > Rcpp::sourceCpp("~/git/stackoverflow/67006975/answer.cpp")
    
    > Generate()
         [,1] [,2] [,3] [,4] [,5] [,6]
    [1,]    1    1    1    1    1    1
    [2,]    1    1    1    1    1    1
    [3,]    1    1    1    1    1    1
    [4,]    1    1    1    1    1    1
    [5,]    1    1    1    1    1    1
    >