任何人都可以解释以下行为吗?我不理解或发现的功能?
[当声明新的NumericMatrix
,y
作为原始矩阵x
乘以标量c
时,标量/矩阵乘法的顺序很重要。如果我将原始矩阵放在左侧,然后将标量乘以右侧(例如NumericMatrix y = x * c;
),则可以得到期望的结果。 (y
是其条目为NumericMatrix
而x_ij * c
保持不变的x
。
但是,如果我将左边的标量和右边的矩阵相乘(例如NumericMatrix y = c * x;
),那么我将得到奇怪的行为。原始矩阵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
第二个例子:使用
int
没问题
#include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] int testfun2(int x) { int y = x * 2; std::cout << x << "\n"; // x is unmodified int z = 2 * x; std::cout << x << "\n"; // x is still unmodified return x; } /*** R x <- 2 testfun2(x = x) print(x) */
输出如下。
> x <- 2 > testfun2(x = x) 2 2 [1] 2 > print(x) [1] 2
第三示例:使用
NumericVector
没问题
#include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericVector testfun(NumericVector x) { NumericVector y(x.length()); y = x * 2; std::cout << x << "\n"; // x is unmodified y = 2 * x; std::cout << x << "\n"; // x is still unmodified return x; } /*** R x <- rep(2, 3) print(x) y <- testfun(x = x) print(y) print(x) */
输出如下。
> x <- rep(2, 3) > print(x) [1] 2 2 2 > y <- testfun(x = x) 2 2 2 2 2 2 > print(y) [1] 2 2 2 > print(x) [1] 2 2 2
这是我的会话信息
> 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时,......>
这个问题发布得太久了,它的意思隐藏了。我们不需要第二和第三示例。我们需要的只是此代码: