Recently, a question has led me to the fact that syntactic sugar for *to Rcppnot work as expected. In a related question, the user is trying to multiply the matrix by a scalar.
R code
Here we are trying to reach in Rcpp, but now in plain R:
> m <- matrix(0:3, 2, 2)
> m * 3
[,1] [,2]
[1,] 0 6
[2,] 3 9
Rcpp Code
I have created some minimal examples demonstrating both the problem described above and some unexpected behavior along the way. First of all, note that I consistently use it Listas the return type, because it eliminates the need for me to declare the corresponding type in advance:
#include <Rcpp.h>
using namespace Rcpp;
List FooMat() {
NumericMatrix tmp(2,2);
for (int i = 0; i < 4; i++) {
tmp[i] = i;
}
return List::create(tmp);
}
List FooMat2() {
NumericMatrix tmp(2,2);
for (int i = 0; i < 4; i++) {
tmp[i] = i;
}
NumericVector x(1);
x[1] = 3;
return List::create(tmp * x);
}
List FooMat3() {
NumericMatrix tmp(2,2);
for (int i = 0; i < 4; i++) {
tmp[i] = i;
}
NumericVector x(1);
x[1] = 3;
return List::create(tmp * x[1]);
}
List FooMat4() {
NumericMatrix tmp(2,2);
for (int i = 0; i < 4; i++) {
tmp[i] = i;
}
return List::create(tmp * 3);
}
Now, if we select a file, we get an odd behavior:
> FooMat()
[[1]]
[,1] [,2]
[1,] 0 2
[2,] 1 3
> FooMat2()
[[1]]
[1] 0.000000e+00 3.000000e+00 1.388988e-309 2.083483e-309
> FooMat3()
[[1]]
[1] 0 3 6 9
> FooMat4()
[[1]]
[1] 0 3 6 9
-, *, Rcpp, -, . , NumericVector, FooMat2(), .