任何人都可以解释以下行为吗?
[当声明新的NumericMatrix
,y
作为原始矩阵x
乘以标量c
时,标量/矩阵乘法的顺序很重要。如果我将左边的标量和右边的矩阵相乘(例如NumericMatrix y = c * x;
),那么我会得到奇怪的行为。原始矩阵x
已更改!
但是,如果我将原始矩阵放在左侧,然后将标量乘以右侧(例如NumericMatrix y = x * c;
,则x
保持不变。
这似乎不会影响其他数据类型。我已经用int
和NumericVector
进行了测试。
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)
*/
输出如下。
> 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
这是我的会话信息
> 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
任何人都可以解释以下行为吗?当声明一个新的NumericMatrix y作为原始矩阵x乘以标量c时,标量/矩阵乘法的顺序很重要。如果我...
这个问题发布得太久了,它的意思隐藏了。我们不需要第二和第三示例。我们需要的只是此代码: