[Rcpp-devel] Returning a list of matrices: Interesting difference: Sometimes need wrap(); sometimes not
Søren Højsgaard
sorenh at math.aau.dk
Sun Sep 9 10:27:25 CEST 2012
Dear list,
Given a matrix X, I want to return a list containing X and its inverse: This works:
library(inline)
code <- '
arma::mat X = as<arma::mat>(X_);
arma::mat Xinv = inv( X );
return Rcpp::List::create(Rcpp::Named("X", X),Rcpp::Named("Xinv", Xinv));'
sol <- cxxfunction(signature(X_ = "matrix"), code, plugin = "RcppArmadillo", verbose=F)
M <- matrix(c(1,2,3,4),nr=2)
> sol(M)
$X
[,1] [,2]
[1,] 1 3
[2,] 2 4
$Xinv
[,1] [,2]
[1,] -2 1.5
[2,] 1 -0.5
Now I create a corresponding function (same content) and compile:
#include <Rcpp.h>
#include <RcppArmadillo.h>
RcppExport SEXP sol1 ( SEXP X_ ){
using namespace Rcpp;
arma::mat X = as<arma::mat>(X_);
arma::mat Xinv = inv( X );
return Rcpp::List::create(Rcpp::Named("X", X),Rcpp::Named("Xinv", Xinv));
}
> dyn.load("sol.dll")
> .Call("sol1", M)
$X
[1] 1 2 3 4
$Xinv
[1] -2.0 1.0 1.5 -0.5
> dyn.unload("sol.dll")
So the dim attributes are lost. Interesting difference to the inline approach.
On the other hand, if I use wrap() I get what I want:
RcppExport SEXP sol2 ( SEXP X_ ){
using namespace Rcpp;
arma::mat X = as<arma::mat>(X_);
arma::mat Xinv = inv( X );
return Rcpp::List::create(Rcpp::Named("X", wrap(X)),Rcpp::Named("Xinv", wrap(Xinv)));
}
> dyn.load("sol.dll")
> .Call("sol2", M)
$X
[,1] [,2]
[1,] 1 3
[2,] 2 4
$Xinv
[,1] [,2]
[1,] -2 1.5
[2,] 1 -0.5
> dyn.unload("sol.dll")
Can anyone point me to why there are these differences whether I use inline or not. I must overlook something trivial.
Regards
Søren
More information about the Rcpp-devel
mailing list