<div dir="ltr">In the latter case the integer matrix is "converted" to a numeric matrix via a copy which is why your modification doesn't work.<div><br></div><div>That said, modifying an object in place violates R's language semantics and could lead to incorrect computations (i.e. users expect that objects are immutable and this is part of what ensures the integrity of computations) so this is strongly discouraged.</div></div><div class="gmail_extra"><br><div class="gmail_quote">On Sun, Aug 7, 2016 at 7:00 AM, Kaspar Märtens <span dir="ltr"><<a href="mailto:kaspar.martens@gmail.com" target="_blank">kaspar.martens@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div dir="ltr">Hi, <div><br></div><div>When experimenting with the following toy function, </div><div><br></div><div><div>// [[Rcpp::export]]</div><div>void modify_matrix(NumericMatrix A){</div><div>  A(0, 0) = 5;</div><div>}</div></div><div><br></div><div>and applying this on matrices defined in R, I occasionally noticed unexpected behaviour (as it turns out, on integer matrices). <br></div><div><br></div><div>### Example 1 (works as expected)</div><div><br></div><div><div>A = matrix(0, 2, 2)</div><div>modify_matrix(A)</div><div>A</div><div><br></div><div>##      [,1] [,2]</div><div>## [1,]    5    0</div><div>## [2,]    0    0</div></div><div><br></div><div>### Example 2 (does not modify the matrix)</div><div><br></div><div><div>A = matrix(1:4, 2, 2)</div><div>modify_matrix(A)</div><div>A</div><div><br></div><div>##      [,1] [,2]</div><div>## [1,]    1    3</div><div>## [2,]    2    4</div></div><div><br></div><div>I realised that in the latter case, A consists of integers, so I guess I should be using an IntegerMatrix version of my function instead. However, shouldn't Rcpp detect the type mismatch between NumericMatrix and IntegerMatrix?</div><div><br></div><div>Best,</div><div>Kaspar</div><div><br></div></div>
<br>______________________________<wbr>_________________<br>
Rcpp-devel mailing list<br>
<a href="mailto:Rcpp-devel@lists.r-forge.r-project.org">Rcpp-devel@lists.r-forge.r-<wbr>project.org</a><br>
<a href="https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel" rel="noreferrer" target="_blank">https://lists.r-forge.r-<wbr>project.org/cgi-bin/mailman/<wbr>listinfo/rcpp-devel</a><br></blockquote></div><br></div>