Can anyone explain the following behavior?
When declaring a new NumericMatrix
, y
, as the original matrix, x
, multiplied by a scalar, c
, the order of the scalar/matrix multiplication matters. If I multiply the scalar on the left and the matrix on the right (e.g. NumericMatrix y = c * x;
), then I get bizarre behavior. The original matrix, x
, is changed!
However if I put the original matrix to the left and multiply the scalar on the right (e.g. NumericMatrix y = x * c;
), x
remains unchanged.
This doesn't seem to affect other data types. I've tested with int
and NumericVector
.
Example: Problem appears when using NumericMatrix
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix testfun(NumericMatrix x) {
NumericMatrix y(x.rows(), x.cols());
y = x * 2;
std::cout << x; // x is unmodified
y = 2 * x;
std::cout << x; // x is now modified
return x;
}
/*** R
x <- matrix(2, nrow = 3, ncol = 3)
print(x)
y <- testfun(x = x)
print(y)
print(x)
*/
The output is as follows.
> x <- matrix(2, nrow = 3, ncol = 3)
> print(x)
[,1] [,2] [,3]
[1,] 2 2 2
[2,] 2 2 2
[3,] 2 2 2
> y <- testfun(x = x)
2.00000 2.00000 2.00000
2.00000 2.00000 2.00000
2.00000 2.00000 2.00000
4.00000 4.00000 4.00000
4.00000 4.00000 4.00000
4.00000 4.00000 4.00000
> print(y)
[,1] [,2] [,3]
[1,] 4 4 4
[2,] 4 4 4
[3,] 4 4 4
> print(x)
[,1] [,2] [,3]
[1,] 4 4 4
[2,] 4 4 4
[3,] 4 4 4
Here is my session info
> sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Catalina 10.15.1
Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] compiler_3.6.1 tools_3.6.1 RcppArmadillo_0.9.800.1.0
[4] Rcpp_1.0.2 RcppProgress_0.4.1 packrat_0.5.0
[7] RcppParallel_4.4.4
.