[Rcpp-devel] Pass matrix by copy

soeren.vogel at posteo.ch soeren.vogel at posteo.ch
Tue Apr 14 19:15:20 CEST 2015


Hello,

I have just noticed that my small Rcpp function changes the original matrix on the R side -- why and how to pass by copy?

Thanks
Sören

<source c++>
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericMatrix test_min( NumericMatrix M ) {
	int n = M.nrow();
	for ( int i = 0; i < n; ++i ) {
		for ( int j = 0; j < n; ++j ) {
			M(i, j) = M(i, j) * 2.0;
		}
	}
	return M;
}
</source>

<source R>
library( 'Rcpp' )
mat <- matrix(runif(4), nrow=2)
sourceCpp('min.cpp')
test_min(mat) # mat * 2
test_min(mat) # mat * 2 * 2
test_min(mat) #...
mat
</source>



More information about the Rcpp-devel mailing list