[Rcpp-devel] Deep copying a matrix

Douglas Bates bates at stat.wisc.edu
Thu Jul 14 22:34:25 CEST 2011


On Thu, Jul 14, 2011 at 12:55 PM, Dirk Eddelbuettel <edd at debian.org> wrote:
>
> On 14 July 2011 at 12:36, Etienne B. Racine wrote:
> | I'm struggling with the copy of my parameters. If I understand correctly, if
> | you ship an int matrix to the function, you'll get a deep copy. However if it's
>
> Wrong.
>
> As Doug alluded to, you need the .clone() method for (intentional) deep
> copies.  In other words, but default all copies are what one could call
> shallow, in fact we simply access the same SEXP structure you had in R.

Minor correction here and at the end of Dirk's reply - Rcpp::clone is
a stand-alone function, not a method.  I think I learned this when
trying to use it as a method.

> | a numeric matrix, then there's no copy and you get a matrix pointing on your R
> | matrix. That's funny when you try to debug as one might work and the other not.
>
> It basically boils down to user error on your side, and our inability to do
> much about this code-wise.  Let me recap:
>
> | Here's an illustration
> | library(Rcpp); library(inline)
> |
> | f1 <- cxxfunction(signature(origin="numeric"), body = "
> |                   Rcpp::NumericMatrix m_source(origin);
>
> So you want a _numeric_ matrix but ...
>
> |                   m_source(0,0) = 0;
> |                   cout << origin << endl << m_source << endl ;
> | ",
> |                   include = "using namespace std;",
> |                   plugin="Rcpp")
> |
> | m <- matrix(1:4,2,2)
>
> you send in an _integer matrix_ and because the types do not mix, we must
> copy. This is a little esoteric, but we discuss that in one or two places and
> it has come up here too
>
> | x <- f1(m)
> |
> | #0x9c7fe18
> | #0xb416a1a8  # different
>
> Because of the int != numeric issue.
>
> | m
> | #     [,1] [,2]
> | #[1,]    1    3
> | #[2,]    2    4
> | m <- matrix(1:4/2,2,2)
> | x <- f1(m)
> | #0xb416a090
> | #0xb416a090  # no different
>
> Because numeric == numeric.
>
> | m
> | #     [,1] [,2]
> | #[1,]    0  1.5
> | #[2,]    1  2.0
> |
> |
> | Now, what I'd like is to have a (deep) copy of that matrix, whatever the type.
>
> .clone should do that.
>
> Hth, Dirk
>
> --
> Gauss once played himself in a zero-sum game and won $50.
>                      -- #11 at http://www.gaussfacts.com
> _______________________________________________
> 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
>


More information about the Rcpp-devel mailing list