[Rcpp-devel] Pass matrix by copy
Kevin Ushey
kevinushey at gmail.com
Tue Apr 14 19:16:42 CEST 2015
This is by design; we pass objects by reference for efficiency. Use
`Rcpp::clone()` to explicitly duplicate objects.
On Tue, Apr 14, 2015 at 10:15 AM, <soeren.vogel at posteo.ch> wrote:
> 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>
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20150414/5a039dbe/attachment.html>
More information about the Rcpp-devel
mailing list